This module allows you to cache API responses for a specified period of time.
The responses are cached in memory after the first request, up until the function container is removed.
You can check for X-APPEXPRESS-API-CACHE
in the response header, the values will be any one of the below -
-
HIT
- response is cached -
MISS
- response is not cached, probably this is the first request -
EXCLUDED
- the request is excluded for caching response via options or response header -
IGNORED
- the request method is eitherPUT
,POST
orDELETE
which are never cached
Add the middleware like this -
npm install @itznotabug/appexpress-apicache
// import
import AppExpress from '@itznotabug/appexpress';
import * as cache from '@itznotabug/appexpress-apicache';
// setup
const express = new AppExpress();
express.middleware(cache.createApiCache({
excludes: ['/admin'],
timeout: 1000 * 60 * 5 // 5 minutes, use 0 for no expiry!
}));
express.get('/user/paymentMethods', async (req, res) => {
const user = await sdk.getUser(req);
const paymentMethods = await sdk.getPaymentMethods(user);
res.setHeaders({ 'apicache-exclude': true });
res.json({ paymentMethods })
});
express.get('/user/code', async (req, res) => {
const timedContent = await sdk.timedContent(req);
const oneMinute = 60 * 1000;
res.setHeaders({ 'apicache-timeout': oneMinute });
res.json({ timedContent })
});
express.get('/search/results', async (req, res) => {
if (cache.hasCache(req.url)) {
res.empty();
return;
}
const thirtySeconds = 30 * 1000;
const { searchText } = req.params;
const results = await sdk.search(searchText);
res.setHeaders({ 'apicache-timeout': thirtySeconds });
res.json({ results })
});
cache.clearCache(url);
// remove all
cache.clearAllCache();