3.0.0 • Published 6 years ago
cachex v3.0.0
cachex
Cache Hook
Installation
$ npm install cachex --save
Usage
If you have origin SQL query, it is db.js
:
exports.getRows = async function () {
// mock slow query
var rows = await db.query(sql);
return rows;
};
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 yieldable method.
// db_with_cache.js
var cachex = require('cachex');
var db = require('./db');
// cache result 10s
export.getRows = cachex(store, 'db', 'getRows', db.getRows, 10);
Running go:
var db = require('./db_with_cache');
// from db
db.getRows();
// from cache
db.getRows();
// ..10s..pass..
// from db
db.getRows();
License
The MIT license