UNPKG

1.33 kBJavaScriptView Raw
1'use strict';
2var Promise = require('bluebird');
3
4var TRUE = Promise.resolve(true);
5var FALSE = Promise.resolve(false);
6function parseJSON (string) {
7 // so as not to have to deal with the errors
8 return new Promise(function (fullfill) {
9 fullfill(JSON.parse(string));
10 });
11}
12module.exports = MemStore;
13
14function MemStore() {
15 this.store = Object.create(null);
16}
17MemStore.prototype.get = function(key, cb) {
18 key = '$' + key;
19 if (key in this.store) {
20 return parseJSON(this.store[key]).nodeify(cb);
21 } else {
22 var err = new Error('not found');
23 err.notFound = true;
24 return Promise.reject(err).nodeify(cb);
25 }
26};
27MemStore.prototype.put = function(key, value, cb) {
28 key = '$' + key;
29 this.store[key] = JSON.stringify(value);
30 return TRUE.nodeify(cb);
31};
32
33MemStore.prototype.del = function(key, cb) {
34 key = '$' + key;
35 if (key in this.store) {
36 delete this.store[key];
37 return TRUE.nodeify(cb);
38 }
39 return FALSE.nodeify(cb);
40};
41MemStore.prototype.batch = function(array, cb) {
42 var self = this;
43
44 return Promise.all(array.map(function (item) {
45 if (item.type === 'del') {
46 return self.del(item.key);
47 }
48 return self.put(item.key, item.value);
49 })).nodeify(cb);
50};
51MemStore.prototype.clear = function(cb) {
52 this.store = Object.create(null);
53 return TRUE.nodeify(cb);
54};
\No newline at end of file