Skip to content

Helpers

Brod edited this page Jul 14, 2018 · 4 revisions

Jagwah Helpers are small utilities that a regular web application would use.

Overview

Helpers provide an easy way to do common things and they will work well with tree-shaking so if you don't use them they won't bloat your builds. You can access Helper's from the Jagwah.Helpers property.

import { Helpers } from 'jagwah';
​
Helpers[name](...);

http

The http Helper wraps the Fetch API and returns a Promise with the original fetch Response.json() object, if the statusCode of the response is between 200 and 299 (inclusive) it will resolve, otherwise it will reject.

Usage

Currently there are shortcut helpers for GET and POST Methods, it was @8eecf0d2's decision to not include shortcuts for (DELETE, PATCH, etc..) because REST is stupid. However, you can perform a more vanilla fetch request using the Helpers.http.fetch() method and still get access to correctly thrown JSON'd responses.

Helpers.http.get(url [, queryParams, fetchOptions]);
Helpers.http.post(url [, body, fetchOptions]);
Helpers.http.fetch(url, [, fetchOptions]);

Example

The example below shows a HTTP POST request to the url /api/endpoint with a body of { foo: 'bar' } and an expected response type of { baz: boolean }.

import { Helpers } from 'hyperng';
​
interface myResponseType { baz: boolean }
Helpers.http.post<myResponseType>('/api/endpoint', { foo: 'bar' })
  .then(response => {
    // response: myResponseType
  })
  .catch(response => {
    // response: any
  });

sync

The sync Helper is basically a shallow property setter for any HTMLElement objects that have a value property, it's a one-way binding method that will update your object[property] with the elements value when called.

Usage

Helpers.sync(object, property);

Example

The example below will set the email and password properties of the $account.signForm to the value of the input element when the onchange event occurs.

templates/signup.ts

import { Jagwah, Helpers, Template } from 'jagwah';
import { AccountProvider } from '../providers';
​
@Template('signup-form')
export class SignUpForm {
  constructor(
    private renderer: Jagwah.template.render,
    @Inject('$account') private $account: AccountProvider,
  ) {
    return renderer`
      <form onsubmit=${$account.signIn.bind($account)}>
        <input type="email" onchange=${Helpers.sync($account.signUpForm, 'email')}>
        <input type="password" onchange=${Helpers.sync($account.signUpForm, 'password')}>
        <input type="submit">
      </form>
    `
  }
}

providers/account.ts

import { Jagwah, Provider } from 'jagwah';
​
@Provider('$account')
export class AccountProvider {
  public signUpForm: { email: string, password: string };
  constructor() {}
	
  public async signUp() { ... }
}
​
hyperNg.provider(AccountProvider);