Skip to content

Latest commit

 

History

History
365 lines (244 loc) · 11.3 KB

docs.md

File metadata and controls

365 lines (244 loc) · 11.3 KB

Table of Contents

api

A lightweight wrapper around the http module. Provides functions to make API requests with specified HTTP methods.

The functions are as follows:

  • get(url, options) sends a 'GET' request
  • patch(url, body, options) sends a 'PATCH' request
  • post(url, body, options) sends a 'POST' request
  • put(url, body, options) sends a 'PUT' request
  • destroy(url, body, options) sends a 'DELETE' request
  • call(url, method, body, options) sends a request with specified method

Each function can be passed an options object, which will eventually be forwarded to the Fetch API.

Each function returns a promise, which will either resolve with a response object or reject with an HTTPError.

Examples

function getUsers () {
  return api.get('/users', { credentials: 'include' })
}

getUsers()
   .then(res => console.log('The users are', res))
   .catch(err => console.log('An error occurred!', err))

configureApi

A function that returns a configured instance of the api module. This function's argument will be used as the default config for the returned instance.

Note: This configuration can always be overridden by passing in options manually.

Parameters

  • config Object An api configuration object
  • baseApi Object? An existing api instance to extend with the configuration

Examples

const myApi = configureApi({ root: 'http://example.com', mode: 'cors' })

myApi.get('/thing') // A cors request will be made to "http://example.com/thing"

Returns Object A configured api instance

configureHttp

A function that returns a configured instance of the http module. This function's argument will be used as the default config for the returned instance.

Note: This configuration can always be overridden by passing in options manually.

Parameters

  • config Object An http configuration object
  • baseHttp Object? An existing http instance to extend with the configuration

Examples

const myHttp = configureHttp({ root: 'http://example.com', mode: 'cors' })

myHttp('/thing', { method: 'GET' }) // A cors request will be made to "http://example.com/thing"

Returns Object A configured http instance

composeMiddleware

A utility function that composes multiple request middlewares into a single function. This can be used to create more complex before hooks for http.

Parameters

  • middlewares ...Function Functions that receive and return request options

Examples

function addBearerToken () {
   const token = getTokenFromStorage()
   if (token) return { bearerToken: token }
}

function addPathToUrl ({ url }) {
   return {
     url: url + '/some-path'
   }
}

const before = composeMiddleware(
   addBearerToken,
   addPathToUrl,
)

// this will call both middlewares before the request
http('/users', { before })

Returns Function A composed middleware function

http

A wrapper function for the Fetch API that adds default request settings and handles CRSF token logic.

This function adds the following config settings to the given request:

{
  credentials: 'same-origin',
  headers: [
    'Accept': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json'
  ],
  mode: 'same-origin'
}

Any one of these settings can be overriden using the passed-in config object.

In addition to the normal Fetch API settings, the config object may also contain these special settings just for http:

  • url: The url for the request. This can also be passed in directly as the first argument (see shorthand example).
  • root: A path to be appended to the given url (default='').
  • crsf: The name of the meta tag containing the CSRF token (default='csrf-token'). This can be set to false to prevent a token from being sent.
  • before: A function that's called before the request executes. This function is passed the request options and its return value will be added to those options. It can also return a promise that resolves to a new options object.
  • bearerToken: A token to use for bearer auth. If provided, http will add the header "Authorization": "Bearer <bearerToken>" to the request.
  • onSuccess: A function that will be called if the request succeeds. It will be passed the successful response. If it returns a value, http will resolve with this value instead of the response.
  • onFailure: A function that will be called if the request fails. It will be passed the error that was thrown during the request. If it returns a value, http will reject with this value instead of the default error.
  • successDataPath: A path to response data that the promise will resolve with.
  • failureDataPath: A path to the errors that will be included in the HttpError object (default='errors')
  • query: An object that will be transformed into a query string and appended to the request URL.
  • overrideHeaders: A boolean flag indicating whether or not default headers should be included in the request (default=false).
  • camelizeResponse: A boolean flag indicating whether or not to camelize the response keys (default=true). The helper function that does this is also exported from this library as camelizeKeys.
  • decamelizeBody: A boolean flag indicating whether or not to decamelize the body keys (default=true). The helper function that does this is also exported from this library as decamelizeKeys.
  • decamelizeQuery: A boolean flag indicating whether or not to decamelize the query string keys (default=true).
  • parseJsonStrictly: A boolean flag indicating whether or not to return the text of the response body if JSON parsing fails (default=true). If set to true and invalid JSON is received in the response, then null will be returned instead.
  • auth: An object with the following keys { username, password }. If present, http will use basic auth, adding the header "Authorization": "Basic <authToken>" to the request, where <authToken> is a base64 encoded string of username:password.

Type: Function

Parameters

  • config Object An object containing config information for the Fetch request, as well as the extra keys noted above.

Examples

function getUsers () {
  return http({
     url: '/users',
     root: 'www.my.cool.api.com',
     crsf: 'custom-token-name'
  })
}

getUsers()
   .then(res => console.log('The users are', res))
   .catch(err => console.log('An error occurred!', err))

// Shorthand: pass `url` as first argument:
function getUsers () {
  return http('/users', options)
}

Returns Promise A Promise that either resolves with the response or rejects with an HttpError.

HttpError

Extends Error

An error class that is thrown by the http module when a request fails.

In addition to the standard Error attributes, instances of HttpError include the following:

  • status: the status code of the response
  • statusText: the status text of the response
  • response: the full response object
  • message: A readable error message with format <status> - <statusText>

Parameters

  • status Number the status code of the response
  • statusText String the status text of the response
  • response Object the full response object
  • errors Object an object containing error messages associated with the response (optional, default {})

Examples

// Instantiated manually
const MyError = new HttpError(500, 'Something went wrong!')
console.log(MyError.toString()) // "HttpError: 500 - Something went wrong"

// Instantiated by http module
http('/bad-route').catch(err => console.log(err.name)) // -> "HttpError"

isAuthenticated

A helper function to determine if the current user is authenticated. This function accepts an object argument with a context key.

Note, this does not validate the token, it only checks for presence, validation must be done on the server.

Type: Function

Parameters

  • options Object config object containing the context (optional, default {})

Examples

// WITHOUT context

// After sign in
isAuthenticated() // true

// After sign out
isAuthenticated() // false

// WITH context

// After an 'admin' signs in
isAuthenticated({ context: 'admin' }) // true

isAuthenticated({ context: 'non-admin' }) // false

// After sign out
isAuthenticated({ context: 'admin' }) // false

isAuthenticated({ context: 'non-admin' }) // false

Returns Boolean True when the LP Auth Api cookie exists and contains a token. If the context key is present, this function returns true if the user is both authenticated and the specified context is present.

getAuthenticationContext

A helper function to retrieve the authentication context for the authenticated user.

Examples

// After an 'admin' signs in
getAuthenticationContext() // 'admin'

// After a user with no context signs in
getAuthenticationContext() // undefined

// After sign out
getAuthenticationContext() // undefined

Returns (String | Undefined) The context string when the LP Auth Api cookie exists, contains a valid token, and contains a context. Returns undefined when there is no context present, or if the LP Auth API cookie does not exist.