UNPKG

1.21 kBJavaScriptView Raw
1/**
2 * Module dependencies
3 */
4
5var lscache = require('lscache');
6var Hash = require('xxhashjs')(0xABCD);
7var parser = require('hyper-json-immutable-parse');
8
9exports.get = function(host, path, headers, cb) {
10 setTimeout(function() {
11 var key = hash(host, path, headers);
12 cb(null, deserialize(lscache.get(key)));
13 }, 0);
14};
15
16exports.set = function(host, path, headers, response, cb) {
17 var time = parseTime(response[1]);
18 var key = hash(host, path, headers);
19 if (time && response) {
20 lscache.set(key, serialize(response), time);
21 } else {
22 lscache.remove(key);
23 }
24 cb && cb();
25};
26
27exports.remove = function(host, path, cb) {
28 lscache.remove(hash(host, path));
29 cb && cb();
30};
31
32function parseTime(headers) {
33 var control = headers['cache-control'] || '';
34 var parts = control.match(/max-age=([0-9]+)/);
35 if (!parts) return false;
36 return Math.floor(parseInt(parts[1], 10) / 60);
37}
38
39function hash(host, path, headers) {
40 // TODO add vary headers
41 return Hash.update(JSON.stringify([host, path])).digest().toString(36);
42}
43
44function serialize(res) {
45 return '!' + JSON.stringify(res);
46}
47
48function deserialize(res) {
49 if (!res) return res;
50 return JSON.parse(res.slice(1), parser);
51}