1 |
|
2 |
|
3 |
|
4 |
|
5 | var lscache = require('lscache');
|
6 | var Hash = require('xxhashjs')(0xABCD);
|
7 | var parser = require('hyper-json-immutable-parse');
|
8 |
|
9 | exports.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 |
|
16 | exports.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 |
|
27 | exports.remove = function(host, path, cb) {
|
28 | lscache.remove(hash(host, path));
|
29 | cb && cb();
|
30 | };
|
31 |
|
32 | function 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 |
|
39 | function hash(host, path, headers) {
|
40 |
|
41 | return Hash.update(JSON.stringify([host, path])).digest().toString(36);
|
42 | }
|
43 |
|
44 | function serialize(res) {
|
45 | return '!' + JSON.stringify(res);
|
46 | }
|
47 |
|
48 | function deserialize(res) {
|
49 | if (!res) return res;
|
50 | return JSON.parse(res.slice(1), parser);
|
51 | }
|