4.0.0 • Published 4 months ago
cachex v4.0.0
cachex
A cache hook
Installation
npm i cachex --save
Usage
If you have origin SQL query, it is db.js
:
async function getRows() {
// mock a slow query
return await db.query(sql);
}
Before use cachex
, you must provider an cache storage, it can be redis or memcached or memory.
var inMemory = {};
var store = {
get: async function (key) {
return inMemory[key];
},
setex: async function (key, value, expire) {
inMemory[key] = value;
setTimeout(function () {
delete inMemory[key];
}, expire);
}
};
The storage object must have get/setex method.
// db_with_cache.js
import cachex from 'cachex';
import db from './db.js';
// cache result 10s
export const getRows = cachex(store, 'db', 'getRows', db.getRows, 10);
Running go:
import dbx from './db_with_cache.js';
// from db
await dbx.getRows();
// from cache
await dbx.getRows();
// ..10s..pass..
// from db
await dbx.getRows();
License
The MIT license