- api
- configureApi
- configureHttp
- composeMiddleware
- http
- HttpError
- isAuthenticated
- getAuthenticationContext
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'requestpatch(url, body, options)sends a'PATCH'requestpost(url, body, options)sends a'POST'requestput(url, body, options)sends a'PUT'requestdestroy(url, body, options)sends a'DELETE'requestcall(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.
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))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.
configObject An api configuration objectbaseApiObject? An existing api instance to extend with the configuration
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
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.
configObject An http configuration objectbaseHttpObject? An existing http instance to extend with the configuration
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
A utility function that composes multiple request middlewares into a single function.
This can be used to create more complex before hooks for http.
middlewares...Function Functions that receive and return request options
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
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 themetatag containing the CSRF token (default='csrf-token'). This can be set tofalseto 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,httpwill 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,httpwill 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,httpwill 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 ascamelizeKeys.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 asdecamelizeKeys.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 totrueand invalid JSON is received in the response, thennullwill be returned instead.auth: An object with the following keys{ username, password }. If present,httpwill use basic auth, adding the header"Authorization": "Basic <authToken>"to the request, where<authToken>is a base64 encoded string ofusername:password.
Type: Function
configObject An object containing config information for theFetchrequest, as well as the extra keys noted above.
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.
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 responsestatusText: the status text of the responseresponse: the full response objectmessage: A readable error message with format<status> - <statusText>
statusNumber the status code of the responsestatusTextString the status text of the responseresponseObject the full response objecterrorsObject an object containing error messages associated with the response (optional, default{})
// 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"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
optionsObject config object containing the context (optional, default{})
// 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' }) // falseReturns 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.
A helper function to retrieve the authentication context for the authenticated user.
// After an 'admin' signs in
getAuthenticationContext() // 'admin'
// After a user with no context signs in
getAuthenticationContext() // undefined
// After sign out
getAuthenticationContext() // undefinedReturns (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.