Skip to content

Instantly share code, notes, and snippets.

@JiaxiangZheng
Last active November 22, 2016 16:19
Show Gist options
  • Save JiaxiangZheng/c4f7ae67f6d73e9f54286248b8909fd2 to your computer and use it in GitHub Desktop.
Save JiaxiangZheng/c4f7ae67f6d73e9f54286248b8909fd2 to your computer and use it in GitHub Desktop.
a simple cache middleware wrapper for nodejs web server
// cache.js
const debug = console.log;
const nextTick = process.nextTick;
const CACHE = {
check(key, req, res) {
if (this._cache[key]) {
debug('cache %s hit', key);
nextTick(() => {
res.end(this._cache[key]);
});
return;
}
if (this._queue[key]) {
debug('batch operation in queue for key %s', key);
this._queue[key].push((text) => {
res.end(text);
});
return;
}
this._queue[key] = [(text) => {
res.end(text);
}];
setTimeout(() => {
this._cache[key] = "ABCDEFG"; // a large long text
// 缓存过期
setTimeout(() => {
delete this._cache[key];
}, 30 * 1000);
const queue = this._queue;
const q = queue[key];
queue[key] = null;
q.forEach(cb => cb(this._cache[key]));
}, 1000);
},
_cache: {},
_queue: {}
}
// HOW TO USE?
// should only work for API request
const http = require('http');
http.createServer(function (req, res) {
const key = req.url;
console.log(key);
// key can be a hash of url and query data
CACHE.check(key, req, res);
return;
}).listen(3040);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment