-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
97 lines (81 loc) · 1.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* Module dependencies.
*/
var debug = require('debug')('chrome-store');
var Emitter = require('emitter');
var storage = chrome.storage;
var runtime = chrome.runtime;
/**
* Export `Store`
*/
module.exports = Store;
/**
* Initialize a new `Store`.
*
* @param {String} type
* @api public
*/
function Store(type){
if (!(this instanceof Store)) return new Store(type);
this.type = type || 'local';
this.keys = [];
this.obj = {};
}
/**
* Mixins
*/
Emitter(Store);
/**
* Set `key`, `value`.
*
* @param {String} key
* @param {Mixed} value
* @api public
*/
Store.prototype.set = function(key, value, fn){
this.obj[key] = value;
if (fn) this.end(fn);
return this;
};
/**
* Get `key`.
*
* @param {String} key
* @api public
*/
Store.prototype.get = function(key, fn){
this.keys.push(key);
if (fn) this.end(fn);
return this;
};
/**
* End.
*
* @param {Function} fn
* @api public
*/
Store.prototype.end = function(fn){
var type = this.type;
var keys = this.keys;
var set = this.obj;
// get
if (keys.length) {
debug('get %o', keys);
this.keys = [];
storage[type].get(keys, done);
return;
}
// set
this.obj = {};
debug('set %o', set);
storage[type].set(set, done);
// done
function done(value){
var args = [].slice.call(arguments);
var err = runtime.lastError;
var key = keys[0];
if (err) return fn(err);
if (args.length === 1) return fn(null, value[key]);
fn.apply(null, [null].concat(args));
}
};