@itznotabug/appexpress-apicache
v0.0.5
Published
A api caching middleware for AppExpress.
Downloads
40
Readme
AppExpress API Cache Middleware
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 cachedMISS
- response is not cached, probably this is the first requestEXCLUDED
- the request is excluded for caching response via options or response headerIGNORED
- the request method is eitherPUT
,POST
orDELETE
which are never cached
Installation
Add the middleware like this -
npm install @itznotabug/appexpress-apicache
Usage
// 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!
}));
Excluding a particular request -
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 })
});
Different cache timeout for a response -
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 })
});
Check if cache exists for a URL
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 })
});
Clear a cache for url or all cache
cache.clearCache(url);
// remove all
cache.clearAllCache();