Server Cache
- The system will register a cache by default, you can get it from
request.cache
export default async ({cache})=>{
await cache.set('test', { name: 'hallo' },10 * 1000);
const value = await cache.get('test');
return value || 'no data';
}
- You can also manually register cache in the plugin
my-nodestack-app
├── src
│ ├── plugins
│ │ │── cache.js
| ├── routes
│ │ │── customCache
│ │ | │── index.js
├── ndsk.config.js
└── package.json
exports.plugin = {
name: 'customCache',
register: async (server) =>{
const cache = server.cache({ segment: 'customCache', expiresIn: 60 * 60 * 1000 });
server.decorate('request','customCache',cache)
}
}
export default async ({customCache})=>{
await customCache.set('test', { name: 'hallo' },10 * 1000);
const value = await customCache.get('test');
return value || 'no data';
}
Configure redis cache
- You can configure the use of
redis
cache inndsk.config.js
module.exports = (isPro)=>{
return {
server:{
cache:{
name: `ndsk-redis-cache`,
provider: {
constructor: require('@hapi/catbox-redis'),
options: {
host:Redis.host,
port:Redis.port,
password:Redis.password
}
}
}
}
}
}
File caching
- You can configure static file caching in
routes
my-nodestack-app
├── src
│ ├── pages
│ │ │── cache
│ │ │ │── index.js
│ ├── routes
│ │ │── cache
│ │ │ │── index.js
│ ├── static
│ │ │── test.css
├── ndsk.config.js
└── package.json
body{
color: 'red';
}
import Path from 'node:path'
export const options = {
cache: {
privacy:'public', //Allow default (no privacy flag), public (public cache), private (private cache)
expiresIn: 10 * 1000 //Expiration time in ms
}
}
export default (request,h)=>{
return h.file(Path.join(process.cwd(),'static/test.css'));
}
import {useState,useEffect} from 'react'
export default (props)=>{
const [value,setValue] = useState(null)
useEffect(()=>{
fetch('/cache/test').then(res=>res.text()).then(res=>{
setValue(res)
})
},[]);
return (
<html lang="en">
<head>
<title>test</title>
</head>
<body>
{value}
</body>
</html>
);
}
- Visit http://localhost:3000/cache and modify
src/static/test.css
as follows. Refresh the page and the data will not change. Refresh again after 30 seconds to update the latest data.
body{
color: 'red';
}