XHR Cache Module v2.0.2
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.js
.
{
xhrCache: {
apiKey: 'you-can-specify-your-own-key',
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)
and need the apiKey as query params for security reasons
Advanced usage
With XHR cache you can customize the default middleware and the initial value.
Here an example to cache specific categories from a specific store
{
xhrCache: {
resources: [
{
name: 'categories',
request: ({ storeId }) => ({
method: 'get',
url: `api/v1/categories`,
params: {
storeId
}
}),
init: ({ store }) => {
const ctx = { storeId: 'REF' }
const path = `categories/categories-${ctx.storeId}.json`
return store({ path, ctx, identifier: ctx.storeId })
},
middleware: {
path: 'categories/:storeId(\\d*|REF)',
handler: async (params, { get, store }) => {
const ctx = { storeId: params.storeId }
const path = `categories/categories-${ctx.storeId}.json`
if (ctx.storeId === '123') throw Error(`Store with id ${ctx.storeId} doesn't not exist`)
return get(path) || store({ path, ctx, identifier: ctx.storeId })
}
}
}
]
}
}
Injected Methods
store
and get
methods are inject to custom middleware
and init
methods and allows you to interact with the stored files.
store ({ path: String, context: Object (optional), identifier: String (optional) }): Promise
Fetch and store requested content to file system
- path: File system path
- context: Injected and used for axios request
- identifier: Used to generate uniq identifier
get (path): Resource
Get file from filesystem
NuxtJS Plugin
XHR Request provide a nuxtJS plugin to get or refresh resource
getResourceById (resourceId: String): Promise<Resource>
Get resource by id
getResourceByUrl (resourceUrl: String): Promise<Resource>
Get resource by url
refreshResourceById (resourceId: String, apiKey: String)
Refresh resource by id
License
MIT License