cachex
v5.0.0
Published
Cache Hook
Readme
cachex
A cache hook
Features:
- No need to modify any existing code
- Auto generate cache key
- Auto serialize and deserialize data
- Built-in cache penetration solution
Installation
npm i cachex --saveUsage
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 provide a 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();Use with Redis
import { createClient } from 'redis';
const redis = createClient({
// redis connection options
});
await redis.connect();
// cachex will auto serialize/deserialize
const store = {
get: async function (key) {
return await redis.GET(key);
},
setex: async function (key, value, expire) {
await redis.SETEX(key, expire, value);
}
};
// cache result 10s
export const getRows = cachex(store, 'db', 'getRows', db.getRows, 10);License
The MIT license
