-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
116 lines (95 loc) · 2.53 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
var DB = require('./lib/db.js');
function SQLContext(options) {
this.readOnly = options.isReadOnly;
this.db = options.db;
}
function _put(db, key, value, callback) {
db.createOrUpdate(key, value, function(err) {
if(err) {
return callback(err);
}
callback();
});
}
SQLContext.prototype.putObject = function(key, value, callback) {
if(this.readOnly) {
return callback(new Error('write operation on read-only context.'));
}
var json = JSON.stringify(value);
var buf = new Buffer(json, 'utf8');
_put(this.db, key, buf, callback);
};
SQLContext.prototype.putBuffer = function(key, value, callback) {
if(this.readOnly) {
return callback(new Error('write operation on read-only context.'));
}
_put(this.db, key, value, callback);
};
SQLContext.prototype.delete = function (key, callback) {
if(this.readOnly) {
return callback(new Error('write operation on read-only context.'));
}
this.db.remove(key, function(err) {
if(err) {
return callback(err);
}
callback();
});
};
SQLContext.prototype.clear = function (callback) {
if(this.readOnly) {
return callback(new Error('write operation on read-only context.'));
}
this.db.clearAll(callback);
};
function _get(db, key, callback) {
db.find(key, callback);
}
SQLContext.prototype.getObject = function(key, callback) {
_get(this.db, key, function(err, data) {
if(err) {
return callback(err);
}
if(data) {
try {
data = JSON.parse(data.toString('utf8'));
} catch(e) {
return callback(e);
}
}
callback(null, data);
});
};
SQLContext.prototype.getBuffer = function(key, callback) {
_get(this.db, key, callback);
};
function SQLProvider(options) {
this.options = options || {};
this.user = options.user;
}
SQLProvider.isSupported = function() {
return (typeof module !== 'undefined' && module.exports);
};
SQLProvider.prototype.open = function(callback) {
if(!this.user) {
return callback(new Error('missing user'));
}
this.db = new DB(this.options, function(err) {
if (err) {
return callback(err);
}
callback();
});
};
SQLProvider.prototype.getReadOnlyContext = function() {
return new SQLContext({isReadOnly: true, db: this.db});
};
SQLProvider.prototype.getReadWriteContext = function() {
return new SQLContext({isReadOnly: false, db: this.db});
};
// Forward db type constants
SQLProvider.MYSQL = DB.MYSQL;
SQLProvider.SQLITE = DB.SQLITE;
SQLProvider.POSTGRES = DB.POSTGRES;
SQLProvider.MARIADB = DB.MARIADB;
module.exports = SQLProvider;