UNPKG

2.24 kBJavaScriptView Raw
1'use strict';
2
3/* eslint-disable no-restricted-syntax */
4
5const $ = require('./utils');
6
7module.exports = cacheFile => {
8 const cache = $.isFile(cacheFile)
9 ? $.readJSON(cacheFile) || {}
10 : {};
11
12 return {
13 all() {
14 return cache;
15 },
16 rm(key) {
17 delete cache[key];
18 },
19 get(key) {
20 return cache[key];
21 },
22 set(key, val, x) {
23 if (typeof x !== 'undefined') {
24 if (!cache[key]) {
25 cache[key] = {};
26 }
27
28 cache[key][val] = x;
29 } else if (typeof val === 'object') {
30 if (Array.isArray(val)) {
31 cache[key] = [].concat(cache[key] || []).concat(val);
32 } else {
33 cache[key] = cache[key] || {};
34
35 Object.keys(val).forEach(k => {
36 cache[key][k] = val[k];
37 });
38 }
39 } else {
40 cache[key] = val;
41 }
42 },
43 unset(key, prop) {
44 delete cache[key][prop];
45 },
46 find(key) {
47 if (cache[key]) {
48 return {
49 id: key,
50 entry: cache[key],
51 };
52 }
53
54 const keys = Object.keys(cache);
55 const max = keys.length;
56
57 for (let i = 0; i < max; i += 1) {
58 const file = keys[i];
59
60 if (cache[file].id === key) {
61 return {
62 id: file,
63 entry: cache[file],
64 };
65 }
66
67 if (file.indexOf(key) > -1) {
68 return {
69 id: file,
70 entry: cache[file],
71 };
72 }
73 }
74 },
75 each(fn) {
76 Object.keys(cache)
77 .forEach(key => fn(cache[key], key));
78 },
79 save() {
80 if (cacheFile) {
81 Object.keys(cache).forEach(id => {
82 if (cache[id].deleted || !$.exists(id)) {
83 delete cache[id];
84 return;
85 }
86
87 // cleanup
88 delete cache[id]._offset;
89
90 if (cache[id].dirty === false) {
91 delete cache[id].dirty;
92 delete cache[id].mtime;
93 }
94
95 if (!cache[id].mtime) {
96 cache[id].mtime = $.mtime(id);
97 }
98 });
99
100 $.writeJSON(cacheFile, cache, {
101 spaces: 2,
102 });
103 }
104 },
105 reset() {
106 Object.keys(cache).forEach(key => {
107 delete cache[key];
108 });
109 },
110 };
111};