forked from hyperledger/fabric-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
couchdbutil.js
111 lines (86 loc) · 2.85 KB
/
couchdbutil.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
/*
* Copyright IBM Corp. All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
*/
'use strict';
exports.createDatabaseIfNotExists = function (nano, dbname) {
return new Promise((async (resolve, reject) => {
await nano.db.get(dbname, async function (err, body) {
if (err) {
if (err.statusCode == 404) {
await nano.db.create(dbname, function (err, body) {
if (!err) {
resolve(true);
} else {
reject(err);
}
});
} else {
reject(err);
}
} else {
resolve(true);
}
});
}));
}
exports.writeToCouchDB = async function (nano, dbname, key, value) {
return new Promise((async (resolve, reject) => {
try {
await this.createDatabaseIfNotExists(nano, dbname);
} catch (error) {
}
const db = nano.use(dbname);
// If a key is not specified, then this is an insert
if (key == null) {
db.insert(value, async function (err, body, header) {
if (err) {
reject(err);
}
}
);
} else {
// If a key is specified, then attempt to retrieve the record by key
db.get(key, async function (err, body) {
// parse the value
const updateValue = value;
// if the record was found, then update the revision to allow the update
if (err == null) {
updateValue._rev = body._rev
}
// update or insert the value
db.insert(updateValue, key, async function (err, body, header) {
if (err) {
reject(err);
}
});
});
}
resolve(true);
}));
}
exports.deleteRecord = async function (nano, dbname, key) {
return new Promise((async (resolve, reject) => {
try {
await this.createDatabaseIfNotExists(nano, dbname);
} catch (error) {
}
const db = nano.use(dbname);
// If a key is specified, then attempt to retrieve the record by key
db.get(key, async function (err, body) {
// if the record was found, then update the revision to allow the update
if (err == null) {
let revision = body._rev
// update or insert the value
db.destroy(key, revision, async function (err, body, header) {
if (err) {
reject(err);
}
});
}
});
resolve(true);
}));
}