2.0.2 • Published 8 months ago

@lion/ajax v2.0.2

Weekly downloads
171
License
MIT
Repository
github
Last release
8 months ago

Tools >> Ajax >> Overview ||10

Ajax is a small wrapper around fetch which:

  • Allows globally registering request and response interceptors
  • Throws on 4xx and 5xx status codes
  • Supports caching, so a request can be prevented from reaching to network, by returning the cached response.
  • Supports JSON with ajax.fetchJSON by automatically serializing request body and deserializing response payload as JSON, and adding the correct Content-Type and Accept headers.
  • Adds accept-language header to requests based on application language
  • Adds XSRF header to request if the cookie is present and the request is for a mutable action (POST/PUT/PATCH/DELETE) and if the origin is the same as current origin or the request origin is in the xsrfTrustedOrigins list.

Installation

npm i --save @lion/ajax

Relation to fetch

Ajax delegates all requests to fetch. ajax.fetch and ajax.fetchJson have the same function signature as window.fetch, you can use any online resource to learn more about fetch. MDN is a great start.

ajax.fetch

The fetch method of ajax is a very small wrapper around native window.fetch and returns a native Response object, the main differences with native window.fetch are:

  • it will use any caching options that you've configured in the Ajax class
  • it will throw on response statuses between 400 and 600 (native fetch doesn't throw)
  • it will run any interceptors that you've configured
  • it will add a XSRF header to the request if the XSRF cookie is present

Otherwise, you can expect the same usage as from window.fetch. Here are some simple examples:

// A simple GET request
const response = await ajax.fetch('/api/foo');
const data = await response.json(); // or .text(), .clone(), .formData(), etc
// A simple POST request
const response = await ajax.fetch('/api/foo', {
  method: 'POST',
  body: JSON.stringify({ foo: 'bar' }),
});

ajax.fetchJson

The fetchJson method of ajax has some additional features, added for convenience and ease of use. For example, the fetchJson method:

  • adds the accept header with a value of application/json
  • adds the content-type header with a value of application/json, if a request body is provided
  • automatically JSON.stringifies the request body, if one is provided
  • will attempt to parse the response body as JSON if available
    • and also automatically remove a JSON prefix from the response body if one is configured

Note that instead of returning only a Response, fetchJson returns an object containing the Response and a JSON.parse'd body

// A simple GET request
const { response, body } = await ajax.fetchJson('/api/foo');
// body.foo === 'bar';
// A simple POST request
const { response, body } = await ajax.fetchJson('/api/foo', {
  method: 'POST',
  body: { foo: 'bar' },
});

Interceptors

Interceptors are functions that can be used to inspect or modify the Request or Response objects of a network request.

Request interceptors

A request interceptor is a function that takes a Request object, and returns a Request object, or a Response object, and runs before the native window.fetch call is done, allowing you to modify or inspect a request before it's made.

If you return a Response object, the response will be returned by the fetch or fetchJson methods, instead of passing the Request to the native window.fetch function.

Returning a Request:

function addAcceptLanguage(request) {
  request.headers.set('accept-language', 'EN_GB');
  return request;
}

ajax.addRequestInterceptor(addAcceptLanguage);

Returning a Response:

function interceptFooRequest(request) {
  if (request.headers.get('foo')) {
    return Response.json({ foo: 'bar' });
  }

  return request;
}

ajax.addRequestInterceptor(interceptFooRequest);

Request interceptors can be async and will be awaited.

Response interceptors

A response interceptor is a function that takes a Response object, and returns a Response object, and runs after the native window.fetch call is done, allowing you to modify or inspect the response before it's returned by fetch/fetchJson.

async function rewriteFoo(response) {
  const body = await response.clone().text();

  return new Response(body.replaceAll('foo', 'bar'), response);
}

ajax.addResponseInterceptor(rewriteFoo);

Response interceptors can be async and will be awaited.

Ajax class options

PropertyTypeDefault ValueDescription
addAcceptLanguagebooleantrueWhether to add the Accept-Language header from the data-localize-lang document property
addCachingbooleanfalseWhether to add the cache interceptor and start storing responses in the cache, even if cacheOptions.useCache is false
xsrfCookieNamestring"XSRF-TOKEN"The name for the Cross Site Request Forgery cookie
xsrfHeaderNamestring"X-XSRF-TOKEN"The name for the Cross Site Request Forgery header
xsrfTrustedOriginsstring[][]List of trusted origins, the XSRF header will also be added if the origin is in this list.
jsonPrefixstring""The prefix to add to add to responses for the .fetchJson functions
cacheOptions.useCachebooleanfalseWhether to use the default cache interceptors to cache requests
cacheOptions.getCacheIdentifierfunctiona function returning the string _default.A function to determine the cache that should be used for each request; used to make sure responses for one session are not used in the next. Can be async.
cacheOptions.methodsstring[]["get"]The HTTP methods to cache reponses for. Any other method will invalidate the cache for this request, see "Invalidating cache", below
cacheOptions.maxAgenumber360000The time to keep a response in the cache before invalidating it automatically
cacheOptions.invalidateUrlsstring[]undefinedUrls to invalidate each time a method not in cacheOptions.methods is encountered, see "Invalidating cache", below
cacheOptions.invalidateUrlsRegexregexundefinedRegular expression matching urls to invalidate each time a method not in cacheOptions.methods is encountered, see "Invalidating cache", below
cacheOptions.requestIdFunctionfunctiona function returning the base url and serialized search parametersFunction to determine what defines a unique URL
cacheOptions.contentTypesstring[]undefinedWhitelist of content types that will be stored to or retrieved from the cache
cacheOptions.maxResponseSizenumberundefinedThe maximum response size in bytes that will be stored to or retrieved from the cache
cacheOptions.maxCacheSizenumberundefinedThe maxiumum total size in bytes of the cache; when the cache gets larger it is truncated

Caching

import { ajax, createCacheInterceptors } from '@lion/ajax';

// Note: getCacheIdentifier can be async
const getCacheIdentifier = () => {
  let userId = localStorage.getItem('lion-ajax-cache-demo-user-id');
  if (!userId) {
    localStorage.setItem('lion-ajax-cache-demo-user-id', '1');
    userId = '1';
  }
  return userId;
};

const TEN_MINUTES = 1000 * 60 * 10; // in milliseconds

const cacheOptions = {
  useCache: true,
  maxAge: TEN_MINUTES,
};

const [cacheRequestInterceptor, cacheResponseInterceptor] = createCacheInterceptors(
  getCacheIdentifier,
  cacheOptions,
);

ajax.addRequestInterceptor(cacheRequestInterceptor);
ajax.addResponseInterceptor(cacheResponseInterceptor);

Or use a custom cache object and add the cache config to the constructor:

import { Ajax } from '@lion/ajax';

const storeButDontRetrieveByDefaultConfig = {
  addCaching: true,
  cacheOptions: {
    getCacheIdentifier,
    useCache: false,
    maxAge: TEN_MINUTES,
  },
};

const customAjax = new Ajax(storeButDontRetrieveByDefaultConfig);

Invalidating the cache

Invalidating the cache, or cache busting, can be done in multiple ways:

  • Going past the maxAge of the cache object
  • Changing cache identifier (e.g. user session or active profile changes)
  • Doing a non GET request to the cached endpoint
    • Invalidates the cache of that endpoint
    • Invalidates the cache of all other endpoints matching invalidatesUrls and invalidateUrlsRegex

Restricting what to cache

The library has a number of options available to restrict what should be cached. They include:

By content type

cacheOptions.contentTypes

If this option is set, it is interpreted as a whitelist for which content types to cache. The content types of a given response is derived from its Content-Type header. If this option is set, responses that do not have a Content-Type header are never added to or retrieved from the cache.

By response size

cacheOptions.maxResponseSize

This option sets a maximum size (in bytes) for a single response to be cached. The size of the response is determined first by looking at the Content-Length header; if this header is not available, the response is inspected (through the blob() function) and its size retrieved.

Limiting the cache size

cacheOptions.maxCacheSize

This option sets a maximum size (in bytes) for the whole cache. The size of a response is determined first by looking at the Content-Length header; if this header is not available, the response is inspected (through the blob() function) and its size retrieved.

If the cache grows larger than the maxCacheSize option, the cache is truncated according to a First-In-First-Out (FIFO) algorithm that simply removes the oldest entries until the cache is smaller than options.maxCacheSize.

2.0.2

8 months ago

2.0.1

10 months ago

2.0.0

10 months ago

1.2.0

1 year ago

1.2.3

1 year ago

1.2.2

1 year ago

1.2.1

1 year ago

1.1.4

1 year ago

1.3.0

1 year ago

1.1.3

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.1.2

2 years ago

1.0.0

2 years ago

0.15.0

3 years ago

0.16.0

3 years ago

0.14.0

3 years ago

0.13.0

3 years ago

0.12.1

3 years ago

0.12.0

3 years ago

0.11.1

3 years ago

0.11.0

4 years ago

0.10.0

4 years ago

0.9.0

4 years ago

0.8.0

4 years ago

0.7.0

4 years ago

0.6.0

4 years ago

0.5.15

4 years ago

0.5.14

4 years ago

0.5.13

4 years ago

0.5.12

4 years ago

0.5.11

4 years ago

0.5.10

4 years ago

0.5.9

4 years ago

0.5.8

4 years ago

0.5.7

4 years ago

0.5.6

4 years ago

0.5.5

4 years ago

0.5.4

4 years ago

0.5.3

4 years ago

0.5.2

4 years ago

0.5.1

4 years ago

0.5.0

4 years ago

0.4.4

4 years ago

0.4.3

5 years ago

0.4.2

5 years ago

0.4.1

5 years ago

0.4.0

5 years ago

0.3.0

5 years ago

0.2.10

5 years ago

0.2.9

5 years ago

0.2.8

5 years ago

0.2.7

5 years ago

0.2.6

5 years ago

0.2.5

5 years ago

0.2.4

5 years ago

0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.20

5 years ago

0.1.19

5 years ago

0.1.18

5 years ago

0.1.17

5 years ago

0.1.16

5 years ago

0.1.15

5 years ago

0.1.14

5 years ago

0.1.13

5 years ago

0.1.12

6 years ago

0.1.11

6 years ago

0.1.10

6 years ago

0.1.9

6 years ago

0.1.8

6 years ago

0.1.7

6 years ago

0.1.6

6 years ago

0.1.5

6 years ago

0.1.4

6 years ago

0.1.3

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago