Lion Logo Lion Guides Components Docs Blog Toggle darkmode

Ajax: Features

GET request

POST request

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

const response = await ajax.request('/api/users', {
  method: 'POST',
  body: JSON.stringify({ username: 'steve' }),
});
const newUser = await response.json();

JSON requests

We usually deal with JSON requests and responses. With requestJson you don't need to specifically stringify the request body or parse the response body.

The result will have the Response object on .response property, and the decoded json will be available on .body.

GET JSON request

POST JSON request

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

const { response, body } = await ajax.requestJson('/api/users', {
  method: 'POST',
  body: { username: 'steve' },
});

Error handling

Different from fetch, ajax throws when the server returns a 4xx or 5xx, returning the request and response:

Fetch Polyfill

For IE11 you will need a polyfill for fetch. You should add this on your top level layer, e.g. your application.

This is the polyfill we recommend. It also has a section for polyfilling AbortController

Ajax Cache

A caching library that uses @lion/ajax and adds cache interceptors to provide caching for use in frontend services.

The request interceptor's main goal is to determine whether or not to return the cached object. This is done based on the options that are being passed.

The response interceptor's goal is to determine when to cache the requested response, based on the options that are being passed.

Getting started

Consume the global ajax instance and add the interceptors to it, using a cache configuration which is applied on application level. If a developer wants to add specifics to cache behavior they have to provide a cache config per action (get, post, etc.) via cacheOptions field of local ajax config, see examples below.

Note: make sure to add the interceptors only once. This is usually done on app-level

import {
  ajax,
  cacheRequestInterceptorFactory,
  cacheResponseInterceptorFactory,
} from '@lion-web/ajax.js';

const globalCacheOptions = {
  useCache: true,
  timeToLive: 1000 * 60 * 5, // 5 minutes
};
// Cache is removed each time an identifier changes,
// for instance when a current user is logged out
const getCacheIdentifier = () => getActiveProfile().profileId;

ajax.addRequestInterceptor(cacheRequestInterceptorFactory(getCacheIdentifier, globalCacheOptions));
ajax.addResponseInterceptor(
  cacheResponseInterceptorFactory(getCacheIdentifier, globalCacheOptions),
);

const { response, body } = await ajax.requestJson('/my-url');

Alternatively, most often for subclassers, you can extend or import AjaxClient yourself, and pass cacheOptions when instantiating the ajax singleton.

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

export const ajax = new AjaxClient({
  cacheOptions: {
    useCache: true,
    timeToLive: 1000 * 60 * 5, // 5 minutes
    getCacheIdentifier: () => getActiveProfile().profileId,
  },
});

Ajax cache example

Let's assume that we have a user session, for this demo purposes we already created an identifier function for this and set the cache interceptors.

We can see if a response is served from the cache by checking the response.fromCache property, which is either undefined for normal requests, or set to true for responses that were served from cache.

You can also change the cache options per request, which is handy if you don't want to remove and re-add the interceptors for a simple configuration change.

In this demo, when we fetch naga, we always pass useCache: false so the Response is never a cached one.

Invalidating cache

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

  • Going past the timeToLive 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

Time to live

In this demo we pass a timeToLive of three seconds. Try clicking the fetch button and watch fromCache change whenever TTL expires.

After TTL expires, the next request will set the cache again, and for the next 3 seconds you will get cached responses for subsequent requests.

Changing cache identifier

For this demo we use localStorage to set a user id to '1'.

Now we will allow you to change this identifier to invalidate the cache.

Non-GET request

In this demo we show that by doing a PATCH request, you invalidate the cache of the endpoint for subsequent GET requests.

Try clicking the GET pabu button twice so you see a cached response. Then click the PATCH pabu button, followed by another GET, and you will see that this one is not served from cache, because the PATCH invalidated it.

The rationale is that if a user does a non-GET request to an endpoint, it will make the client-side caching of this endpoint outdated. This is because non-GET requests usually in some way mutate the state of the database through interacting with this endpoint. Therefore, we invalidate the cache, so the user gets the latest state from the database on the next GET request.

Ignore the browser errors when clicking PATCH buttons, JSON files (our mock database) don't accept PATCH requests.

Invalidate Rules

There are two kinds of invalidate rules:

  • invalidateUrls (array of URL like strings)
  • invalidateUrlsRegex (RegExp)

If a non-GET method is fired, by default it only invalidates its own endpoint. Invalidating /api/users cache by doing a PATCH, will not invalidate /api/accounts cache.

However, in the case of users and accounts, they may be very interconnected, so perhaps you do want to invalidate /api/accounts when invalidating /api/users.

This is what the invalidate rules are for.

In this demo, invalidating the pabu endpoint will invalidate naga, but not the other way around.

For invalidateUrls you need the full URL e.g. <protocol>://<domain>:<port>/<url> so it's often easier to use invalidateUrlsRegex