-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcouchbase.js
53 lines (49 loc) · 1.48 KB
/
couchbase.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
const couchbase = require('couchbase'),
Promise = require('bluebird'),
N1qlQuery = couchbase.N1qlQuery,
connectedBuckets = {};
module.exports = (host, bucket, username, userPassword) => {
const cluster = new couchbase.Cluster(host, {
operation_timeout: 5000
});
// RBAC (Role Based Access Control) Authentication,
// See https://docs.couchbase.com/server/5.1/security/security-rbac-user-management.html
cluster.authenticate(username, userPassword);
const connect = () => {
return new Promise((resolve, reject) => {
if (connectedBuckets[bucket]) {
return resolve(connectedBuckets[bucket]);
}
connectedBuckets[bucket] = cluster.openBucket(bucket, err => {
if (err) {
return reject(err);
}
connectedBuckets[bucket] = Promise.promisifyAll(connectedBuckets[bucket]);
return resolve(connectedBuckets[bucket]);
});
});
};
return {
connect,
queryDB: query => {
return connect().then(bucket => bucket.queryAsync(N1qlQuery.fromString(query)));
},
getDoc: docId => {
return connect()
.then(bucket => bucket.getAsync(docId))
.then(res => res);
},
createDoc: (key, json, option) => {
return connect().then(bucket => {
json.dateCreated = +new Date();
return bucket.insertAsync(key, json, option);
});
},
updateDoc: function(docId, doc, cas) {
if (cas) {
return connect().then(bucket => bucket.replaceAsync(docId, doc, { cas: cas }));
}
return connect().then(bucket => bucket.upsertAsync(docId, doc));
}
};
};