-
Notifications
You must be signed in to change notification settings - Fork 146
/
cloudantStorage.js
398 lines (372 loc) · 14.5 KB
/
cloudantStorage.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/**
* Copyright 2014, 2019 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var Cloudant = require('@cloudant/cloudant');
var util = require('util');
var fs = require('fs');
var settings;
var appname;
var flowDb = null;
var currentFlowRev = null;
var currentSettingsRev = null;
var currentCredRev = null;
var libraryCache = {};
function prepopulateFlows(resolve) {
var key = appname + "/" + "flow";
flowDb.get(key, function (err, doc) {
if (err) {
var promises = [];
if (fs.existsSync(__dirname + "/defaults/flow.json")) {
try {
var flow = fs.readFileSync(__dirname + "/defaults/flow.json", "utf8");
var flows = JSON.parse(flow);
util.log("[cloudantStorage] Installing default flow");
promises.push(cloudantStorage.saveFlows(flows));
} catch (err2) {
util.log("[cloudantStorage] Failed to save default flow");
util.log(err2);
}
} else {
util.log("[cloudantStorage] No default flow found");
}
if (fs.existsSync(__dirname + "/defaults/flow_cred.json")) {
try {
var cred = fs.readFileSync(__dirname + "/defaults/flow_cred.json", "utf8");
var creds = JSON.parse(cred);
util.log("[cloudantStorage] Installing default credentials");
promises.push(cloudantStorage.saveCredentials(creds));
} catch (err2) {
util.log("[cloudantStorage] Failed to save default credentials");
util.log(err2);
}
} else {
util.log("[cloudantStorage] No default credentials found");
}
Promise.all(promises).then(function () {
resolve();
});
} else {
// Flows already exist - leave them alone
resolve();
}
});
}
var cloudantStorage = {
init: function (_settings) {
settings = _settings.cloudantService || {};
if (!settings) {
var err = Promise.reject("cloudantStorage settings not found");
err.catch(err => {});
return err;
}
// This is resulting in Access Denined errors when using IAM
//var couchDb = Cloudant({ vcapInstanceName: settings.name, vcapServices: JSON.parse(process.env.VCAP_SERVICES) });
var couchDb = Cloudant(settings.url);
appname = settings.prefix || require('os').hostname();
var dbname = settings.db || "nodered";
return new Promise(function (resolve, reject) {
couchDb.db.get(dbname, function (err, body) {
if (err) {
couchDb.db.create(dbname, function (err, body) {
if (err) {
reject("Failed to create database: " + err);
} else {
flowDb = couchDb.use(dbname);
flowDb.insert({
views: {
flow_entries_by_app_and_type: {
map: function (doc) {
var p = doc._id.split("/");
if (p.length > 2 && p[2] == "flow") {
var meta = { path: p.slice(3).join("/") };
emit([p[0], p[2]], meta);
}
}
},
lib_entries_by_app_and_type: {
map: function (doc) {
var p = doc._id.split("/");
if (p.length > 2) {
if (p[2] != "flow") {
var pathParts = p.slice(3, -1);
for (var i = 0; i < pathParts.length; i++) {
emit([p[0], p[2], pathParts.slice(0, i).join("/")], { dir: pathParts.slice(i, i + 1)[0] });
}
var meta = {};
for (var key in doc.meta) {
meta[key] = doc.meta[key];
}
meta.fn = p.slice(-1)[0];
emit([p[0], p[2], pathParts.join("/")], meta);
}
}
}
}
}
}, "_design/library", function (err, b) {
if (err) {
reject("Failed to create view: " + err);
} else {
prepopulateFlows(resolve);
}
});
}
});
} else {
flowDb = couchDb.use(dbname);
prepopulateFlows(resolve);
}
});
});
},
getFlows: function () {
var key = appname + "/" + "flow";
return new Promise(function (resolve, reject) {
flowDb.get(key, function (err, doc) {
if (err) {
if (err.statusCode != 404) {
reject(err.toString());
} else {
resolve([]);
}
} else {
currentFlowRev = doc._rev;
resolve(doc.flow);
}
});
});
},
saveFlows: function (flows) {
var key = appname + "/" + "flow";
return new Promise(function (resolve, reject) {
var doc = { _id: key, flow: flows };
if (currentFlowRev) {
doc._rev = currentFlowRev;
}
flowDb.insert(doc, function (err, db) {
if (err) {
reject(err.toString());
} else {
currentFlowRev = db.rev;
resolve();
}
});
});
},
getCredentials: function () {
var key = appname + "/" + "credential";
return new Promise(function (resolve, reject) {
flowDb.get(key, function (err, doc) {
if (err) {
if (err.statusCode != 404) {
reject(err.toString());
} else {
resolve({});
}
} else {
currentCredRev = doc._rev;
resolve(doc.credentials);
}
});
});
},
saveCredentials: function (credentials) {
var key = appname + "/" + "credential";
return new Promise(function (resolve, reject) {
var doc = { _id: key, credentials: credentials };
if (currentCredRev) {
doc._rev = currentCredRev;
}
flowDb.insert(doc, function (err, db) {
if (err) {
reject(err.toString());
} else {
currentCredRev = db.rev;
resolve();
}
});
});
},
getSettings: function () {
var key = appname + "/" + "settings";
return new Promise(function (resolve, reject) {
flowDb.get(key, function (err, doc) {
if (err) {
if (err.statusCode != 404) {
reject(err.toString());
} else {
resolve({});
}
} else {
currentSettingsRev = doc._rev;
resolve(doc.settings);
}
});
});
},
saveSettings: function (settings) {
var key = appname + "/" + "settings";
return new Promise(function (resolve, reject) {
var doc = { _id: key, settings: settings };
if (currentSettingsRev) {
doc._rev = currentSettingsRev;
}
flowDb.insert(doc, function (err, db) {
if (err) {
reject(err.toString());
} else {
currentSettingsRev = db.rev;
resolve();
}
});
});
},
getAllFlows: function () {
var key = [appname, "flow"];
return new Promise(function (resolve, reject) {
flowDb.view('library', 'flow_entries_by_app_and_type', { key: key }, function (e, data) {
if (e) {
reject(e.toString());
} else {
var result = {};
for (var i = 0; i < data.rows.length; i++) {
var doc = data.rows[i];
var path = doc.value.path;
var parts = path.split("/");
var ref = result;
for (var j = 0; j < parts.length - 1; j++) {
ref['d'] = ref['d'] || {};
ref['d'][parts[j]] = ref['d'][parts[j]] || {};
ref = ref['d'][parts[j]];
}
ref['f'] = ref['f'] || [];
ref['f'].push(parts.slice(-1)[0]);
}
resolve(result);
}
});
});
},
getFlow: function (fn) {
if (fn.substr(0) != "/") {
fn = "/" + fn;
}
var key = appname + "/lib/flow" + fn;
return new Promise(function (resolve, reject) {
flowDb.get(key, function (err, data) {
if (err) {
reject(err);
} else {
resolve(data.data);
}
});
});
},
saveFlow: function (fn, data) {
if (fn.substr(0) != "/") {
fn = "/" + fn;
}
var key = appname + "/lib/flow" + fn;
return new Promise(function (resolve, reject) {
var doc = { _id: key, data: data };
flowDb.get(key, function (err, d) {
if (d) {
doc._rev = d._rev;
}
flowDb.insert(doc, function (err, d) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
},
getLibraryEntry: function (type, path) {
if (path != "" && path.substr(0, 1) != "/") {
var key = appname + "/lib/" + type + "/" + path;
} else {
var key = appname + "/lib/" + type + path;
}
if (libraryCache[key]) {
return Promise.resolve(libraryCache[key]);
}
return new Promise(function (resolve, reject) {
flowDb.get(key, function (err, doc) {
if (err) {
if (path.substr(-1, 1) == "/") {
path = path.substr(0, path.length - 1);
}
var qkey = [appname, type, path];
flowDb.view('library', 'lib_entries_by_app_and_type', { key: qkey }, function (e, data) {
if (e) {
reject(e);
} else {
var dirs = [];
var files = [];
for (var i = 0; i < data.rows.length; i++) {
var row = data.rows[i];
var value = row.value;
if (value.dir) {
if (dirs.indexOf(value.dir) == -1) {
dirs.push(value.dir);
}
} else {
files.push(value);
}
}
libraryCache[key] = dirs.concat(files);
resolve(libraryCache[key]);
}
});
} else {
libraryCache[key] = doc.body;
resolve(doc.body);
}
});
});
},
saveLibraryEntry: function (type, path, meta, body) {
var p = path.split("/"); // strip multiple slash
p = p.filter(Boolean);
path = p.slice(0, p.length).join("/")
if (path != "" && path.substr(0, 1) != "/") {
path = "/" + path;
}
var key = appname + "/lib/" + type + path;
return new Promise(function (resolve, reject) {
var doc = { _id: key, meta: meta, body: body };
flowDb.get(key, function (err, d) {
if (d) {
doc._rev = d._rev;
}
flowDb.insert(doc, function (err, d) {
if (err) {
reject(err);
} else {
var p = path.split("/");
for (var i = 0; i < p.length; i++) {
delete libraryCache[appname + "/lib/" + type + (p.slice(0, i).join("/"))]
}
libraryCache[key] = body;
resolve();
}
});
});
});
}
};
module.exports = cloudantStorage;