This repository has been archived by the owner on Aug 29, 2024. It is now read-only.
forked from decentralized-identity/element
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ElementCouchDBAdapter.js
98 lines (89 loc) · 2.07 KB
/
ElementCouchDBAdapter.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
const NodeCouchDb = require('node-couchdb');
class ElementCouchDBAdapter {
constructor({ name, remote, host }) {
if (remote) {
const urlRegex = /https:\/\/(.*):(.*)@(.*)\/(.*)/;
const parts = urlRegex.exec(remote);
this.name = name;
this.couch = new NodeCouchDb({
host: parts[3],
protocol: 'https',
port: 443,
auth: {
user: parts[1],
pass: parts[2],
},
});
} else {
this.name = name;
this.couch = new NodeCouchDb({
host,
protocol: 'http',
port: 5984,
auth: {
user: 'admin',
pass: 'password',
},
});
}
}
async init() {
if (!this.created) {
await this.couch.createDatabase(this.name).catch(err => {
// Sometimes the db already exists
if (err.body.error !== 'file_exists') {
throw err;
}
});
this.created = true;
}
}
async write(id, data) {
await this.init();
const payload = {
_id: id,
id,
...data,
};
try {
await this.couch.insert(this.name, payload);
} catch (e) {
const {
data: { _rev },
} = await this.couch.get(this.name, id);
await this.couch.update(this.name, { _rev, ...payload });
}
return true;
}
async read(id) {
await this.init();
try {
const { data } = await this.couch.get(this.name, id);
return data;
} catch (e) {
return null;
}
}
async readCollection(type) {
await this.init();
const mangoQuery = { selector: { type: { $eq: type } } };
const parameters = {};
const response = await this.couch.mango(this.name, mangoQuery, parameters);
return response.data.docs;
}
async reset() {
await this.init();
await this.couch.dropDatabase(this.name);
this.created = false;
await this.init();
}
async deleteDB() {
await this.init();
await this.couch.dropDatabase(this.name);
this.created = false;
}
async close() {
return this;
}
}
module.exports = ElementCouchDBAdapter;