@autotelic/fastify-swr v0.2.0
Fastify SWR
stale-while-revalidate caching and request de-duplication for fastify
Getting Started
Install
npm i @autotelic/fastify-swrUsage
const fastifySwr = require('@autotelic/fastify-swr')
async function myClient (path, opts = {}) {
const res = await fetch(new URL(`https://example.com/${path}`), opts)
return res.json()
}
async function rootPlugin (fastify, opts) {
await fastify.register(fastifySwr, { handler: myClient, interval: 10 })
fastify.get('/', async function routeHandler (request, reply) {
// By default, the handler's name will be used to name the decorator (see API for mor details)
const content = await fastify.myClient('/endpoint', {
headers: {
accept: 'application/json'
}
})
return content
})
}Example App
To run the example app clone this repo locally, npm i, and then run the following
npm run devOnce running, navigate to localhost:3000 in the browser
API
fastifySwr: FastifyPluginAsync<PluginOpts>
PluginOpts
fastifySwr accepts a PluginOpts object with the following properties:
handler:(key: string, ...args: any[]) => any- Required. The function to be wrapped by the plugin. The return value of thehandlerwill be cached using a stale-while-revalidate caching strategy. Thehandlerwill be called only when the cache is empty or stale. The wrapped handler is accessible as a decorator on the Fastify instance. By default, the handler's name will be used to name the decorator (ie.fastify.myHandler). A custom decorator name can configured using thenameoption.interval:number- The interval in seconds used to determine when a cache will be deemed stale. Defaults to60seconds.name:string- A custom name for the decorator added by this plugin. By default, the name property of thehandlerwill be used.cache:Pick<Map, 'get' | 'set' | 'delete'>- The cache instance for the plugin to use. Must containget,set, anddeletemethods matching the signature of aMap. Method names can be changed using thecacheClientMappingoption below. Defaults tonew Map().cacheClientMapping:{ get: string, set: string, delete: string }- An object used to map custom client method names to the defaultcachemethod names. For example, if using a Redis client you would pass in{ delete: 'del' }.logger:{ debug: (log: string) => void }- A logger to be used for the plugin's debug logs. Defaults tofastify.log(Note: the log-level must be set to 'debug' to view the plugin's logs).