1 | 'use strict';
|
2 | var StringMap = require('stringmap');
|
3 | var StringSet = require('stringset');
|
4 | var Promise = require('bluebird');
|
5 | var TRUE = Promise.resolve(true);
|
6 | module.exports = Batch;
|
7 | function noop(){}
|
8 | function Batch(store) {
|
9 | this.store = store;
|
10 | this.cache = new StringMap();
|
11 | this.deletes = new StringSet();
|
12 | }
|
13 |
|
14 | Batch.prototype.get = function(key, cb) {
|
15 | var self = this;
|
16 | return new Promise(function (resolve, reject) {
|
17 | if (self.cache.has(key)) {
|
18 | resolve(self.cache.get(key));
|
19 | } else if (self.deletes.has(key)) {
|
20 | var err = new Error('not found');
|
21 | err.notFound = true;
|
22 | reject(err);
|
23 | } else {
|
24 | resolve(self.store.get(key));
|
25 | }
|
26 | }).nodeify(cb);
|
27 | };
|
28 | Batch.prototype.put = function(key, value, cb) {
|
29 | var self = this;
|
30 | return new Promise(function (resolve, reject) {
|
31 | self.cache.set(key, value);
|
32 | if (self.deletes.has(key)) {
|
33 | self.deletes.delete(key);
|
34 | }
|
35 | resolve(TRUE);
|
36 | }).nodeify(cb);
|
37 | };
|
38 | Batch.prototype.del = function(key, cb) {
|
39 | var self = this;
|
40 | return new Promise(function (resolve, reject) {
|
41 | self.deletes.add(key);
|
42 | if (self.cache.has(key)) {
|
43 | self.cache.delete(key);
|
44 | }
|
45 | resolve(TRUE);
|
46 | }).nodeify(cb);
|
47 | };
|
48 | Batch.prototype.batch = function(array, cb) {
|
49 | return Promise.all(array.map(function (item){
|
50 | if (item.type === 'del') {
|
51 | return this.del(item.key);
|
52 | }
|
53 | return this.put(item.key, item.value);
|
54 | }, this)).nodeify(cb);
|
55 | };
|
56 | Batch.prototype.save = function () {
|
57 | var items = this.deletes.items().map(function (key) {
|
58 | return {
|
59 | type: 'del',
|
60 | key: key
|
61 | };
|
62 | });
|
63 | items = items.concat(this.cache.map(function (value, key) {
|
64 | return {
|
65 | key: key,
|
66 | value: value
|
67 | };
|
68 | }));
|
69 | this.cache = new StringMap();
|
70 | this.deletes = new StringSet();
|
71 | return this.store.batch(items);
|
72 | }; |
\ | No newline at end of file |