XHR Cache Module v1.0.5
Cache application/json api resources and serve it as static resource
Setup
yarn add @dewib/xhr-cache
npm i @dewib/xhr-cache
Basic usage
Firstly, you need to add xhr-cache
to your Nuxt config.
{
modules: [
[
'@dewib/xhr-cache'
]
]
}
Then you can add all resources that you want to cache by adding it to your Nuxt config.
{
xhrCache: {
rootFolder: 'cache',
rootUrl: 'static',
maxAge: 3600 * 1000
clean: true
resources: [
{
name: 'xhr-cache',
init: false,
request: {
method: 'get',
url: 'http://www.mocky.io/v2/5d9e4c643200002a00329d0a'
},
catch: []
}
]
}
}
Refresh content manually
XHR cache expose routes to refresh a resource manually
All routes are exposed once the first called has been made to the resource or if the init resource option is set to true
The refresh route is generated like this:
path.join(
conf.rootUrl,
'refresh',
id)
Advanced usage
With XHR cache you can customize the default middleware and the initial value.
Here a configuration to cache specific categories from a specific store
{
xhrCache: {
resources: [
{
name: 'categories',
request: ({ storeId }) => ({
method: 'get',
url: `api/v1/categories`,
params: {
storeId
}
}),
init: async ({ store }) => {
const ctx = { storeId: 'REF' }
const path = `categories/categories-${storeId}.json`
await store(path, ctx)
},
middleware: {
path: 'categories/:storeId(\\d*|REF)',
handler: async (req, res, { get, store }) => {
const ctx = { storeId: req.params.storeId }
const path = `categories/categories-${ctx.storeId}.json`
let content = get(path)
if (!content) content = await store(path, ctx)
res.end(JSON.stringify(content))
}
}
}
]
}
}
Methods
Store and get methods are inject to middlware and initial config and allows you to interact with the file system.
store (path, context: optional)
Store requested content to file system
- path: file system path
- context: injected and used for axios request
get (path)
Get file from filesystem
License
MIT License