@data-provider/axios

REST API Data Provider origin addon using Axios

Usage no npm install needed!

<script type="module">
  import dataProviderAxios from 'https://cdn.skypack.dev/@data-provider/axios';
</script>

README

Build status Coverage Status Quality Gate Mutation testing badge

Renovate Last commit Last release

NPM downloads License

Data Provider Axios origin addon

This Data Provider addon provides an API REST data origin using Axios.

Usage

Read the Data Provider docs to learn how to use addons.

Options

Apart of the common Data Provider options, next ones are available:

  • url (String): Url of the API resource.
  • baseUrl (String): Added as prefix to the url option.
  • createVerb (String): HTTP verb to be used in axios requests for create method.
  • readVerb (String): HTTP verb to be used in axios requests for read method.
  • updateVerb (String): HTTP verb to be used in axios requests for update method.
  • deleteVerb (String): HTTP verb to be used in axios requests for delete method.
  • authErrorStatus (Number): Status code that will be considered as an authentication error. When detected, the authErrorHandler function will be executed instead of returning an error.
  • authErrorHandler (Function): Handler that will be executed when an authentication error is received.
    • Arguments:
      • provider (Object): provider instance As first argument, the function will receive the provider itself. This will allow to set custom authentication headers after executing login, as example.
      • retry (Function): As second argument, a retry function is received, it has to be executed in order to retry the authentication failed request.
    • Returns: This function should return a Promise rejected with an error, or the execution of the received retry method.
  • onBeforeRequest (Function): Handler that will be executed before any request method. Useful, for example, to set provider headers just before each request is executed.
    • Arguments:
      • provider (Object): provider instance As first argument, the function will receive the provider itself.
  • onceBeforeRequest (Function): Handler that will be executed once time just before the first request. Useful to set provider configuration, for example.
    • Arguments:
      • provider (Object): provider instance As first argument, the function will receive the provider itself.
  • expirationTime (Number): The cache will be automatically cleaned each expirationTime miliseconds.
  • retries (Number): Number of retries that will be executed when a request fails before definitively failing. Requests will be retried for network errors or a 5xx error on an idempotent request (GET, PUT, PATCH, DELETE).
  • fullResponse (Boolean): If true, the full response object will be used as value, so you can consult headers, etc. If false, only the response.data will be returned, which is the default behavior.
  • validateStatus (Function): Function that will be used to determine if response status has to be considered as failed or success.
    • Arguments:
      • status (Number): Status code of the request.
    • Returns: Should return true for success requests, and false for failed ones.
  • validateResponse (Function): Function that will be used to determine if response has to be considered as failed or success.
    • Arguments:
      • response (Object): Response of the request.
    • Returns: Should return a Promise resolves for success requests, and a Promise rejected with an error for failed ones.
  • errorHandler (Function): Function used to parse errors. The returned value will be setted as error in the provider error property.
    • Arguments:
      • error (Error): Error object produced by a failed request.
    • Returns: Should return a rejected Promise, containing the new Error.
  • axiosConfig (Object): Options for the Axios request. If provided, this object is passed directly to Axios as request configuration.
  • queryStringConfig (Object): Options for the query-string library, which is used under the hood to serialize query string parameters. If provided, this object is passed directly to query-string as options for the stringify method. Default options are the same from the library.

Queries

When querying providers created with this addon, the query object can have one of the next properties:

  • queryString (Object): Object containing all query string parameters to send in the request.
  • urlParams (Object): Keys of the object will be replaced by correspondant url parameters defined in the url as ":param". Please refer to the path-to-regexp package for further info.

When chaining provider queries, the queryString and urlParams objects will be extended with the previous ones

Examples

urlParams example:

import { Axios } from "@data-provider/axios";

const booksModel = new Axios({
  id: "books-model",
  url: "/books/:id",
  baseUrl: "http://foo.api.com"
});

// GET http://foo.api.com/books/2
booksModel.query({
  urlParams: {
    id: 2
  }
}).read();

queryString example:

import { Axios } from "@data-provider/axios";

const booksCollection = new Axios({
  id: "books-collection",
  url: "/books/:id",
  baseUrl: "http://foo.api.com"
});

// GET http://foo.api.com/books/?author=2
booksCollection.query({
  queryString: {
    author: 2
  }
}).read();

Chainability example:

const author2Books = booksCollection.query({
  queryString: {
    author: 2
  }
});

// GET http://foo.api.com/books/?author=2&page=1
author2Books.query({
  queryString: {
    page: 1
  }
}).read();

Custom methods

Apart of the common Data Provider methods, next ones are available:

create(data)

Sends a "create" request. By default, it will use the POST HTTP verb, but this behavior can be changed using the createVerb option. It emits a createSuccess event when the request finish successfully, and automatically cleans the cache of the provider.

Arguments

  • data (Object): Data to be sent as request body.

Example

booksCollection.create({
  title: "1984"
});

update(data)

Sends an "update" request. By default, it will use the PATCH HTTP verb, but this behavior can be changed using the updateVerb option. It emits an updateSuccess event when the request finish successfully, and automatically cleans the cache of the provider.

Arguments

  • data (Object): Data to be sent as request body.

Example

booksCollection.query({
  queryString: {
    id: 2
  }
}).update({
  title: "Fahrenheit 451"
});

delete(data)

Sends a "delete" request. By default, it will use the DELETE HTTP verb, but this behavior can be changed using the deleteVerb option. It emits an deleteSuccess event when the request finish successfully, and automatically cleans the cache of the provider.

Arguments

  • data (Object): Optional. Data to be sent as request body.

Examples

With no request body

booksCollection.query({
  queryString: {
    id: 2
  }
}).delete();

With request body

booksCollection.query().delete({ id: 2 });

When cleaning the cache after a successful request, all methods use the force option under the hood, so the cache will be cleaned inmediately, no matter the cleanCacheThrottle option configured for the provider, as the resource should have changed in the API also inmediatly.

setHeaders(headers)

Defines headers that will be applied to all subsequent requests.

Arguments

  • headers (Object): Each property in the object will be applied as a request header.

Example

booksCollection.setHeaders({
  "Cache-Control": "no-cache"
});

addHeaders(headers)

Add a new header. Current headers will be extended with received headers object, and applied to all subsequent requests:

Arguments

  • headers (Object): Each property in the object will be applied as a request header.

Example

booksCollection.addHeaders({
  Authorization: `Bearer ${token}`
});

Custom Events

Apart of the common events emitted by any Data Provider origin, this addon emits extra events when some custom methods are executed successfully.

Event names are available at the top-level export eventNames:

  • eventNames.CREATE_SUCCESS: Emitted when the create method finish successfully.
  • eventNames.UPDATE_SUCCESS: Emitted when the update method finish successfully.
  • eventNames.DELETE_SUCCESS: Emitted when the delete method finish successfully.

Example

import { eventNames } from "@data-provider/axios";

booksCollection.on(eventNames.CREATE_SUCCESS, () => {
  console.log("A book was created!");
});

Tags

Providers created with this addon will have automatically the axios tag, so you can select all of them together using the providers methods as in:

import { providers } from "@data-provider/core";

providers.getByTag("axios").cleanCache();

Contributing

Contributors are welcome. Please read the contributing guidelines and code of conduct.