-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdb.js
315 lines (311 loc) · 9.16 KB
/
db.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
const _ = require('highland');
const MongoClient = require('mongodb').MongoClient
var db
var mongo
var GENES
var Manager
const init = function(genes) {
GENES = genes
Manager = {}
let promises = GENES.map(function(gene, index) {
return new Promise(function(resolve) {
MongoClient.connect(process.env.PLANA_DB_URL, {useNewUrlParser: true}, function(err, client) {
if (err) console.log(err)
Manager[gene.address] = {
db: client.db(gene.address),
mongo: client
}
resolve()
})
})
})
return Promise.all(promises)
}
const exit = function() {
let promises = Object.keys(Manager).map(function(address) {
return new Promise(function(resolve) {
Manager[address].mongo.close()
resolve()
})
})
return Promise.all(promises)
}
/***************************************
*
* instances()
*
* returns:
*
* [{
* address: [Bitcoin Address],
* names: [Array of Collection Names]
* }, {
* address: [Bitcoin Address],
* names: [Array of Collection Names]
* }]
*
***************************************/
const instances = async function() {
return Object.keys(Manager).map(async function(address) {
let infos = await Manager[address].db.listCollections().toArray()
let collectionNames = infos.map(function(info) { return info.name })
return {
address: address,
names: collectionNames
}
})
}
/***********************************
*
* 1. Create
*
* // Single item insert
* db.create({
* address: PLANARIA_ADDRESS,
* name: COLLECTION_NAME,
* data: DOCUMENT,
* onchunk: function(chunk) { },
* onfinish: function() { },
* })
*
* // Multi item batch insert
* db.create({
* address: PLANARIA_ADDRESS,
* name: COLLECTION_NAME,
* data: DOCUMENT_ARRAY,
* onchunk: function(chunk) { },
* onfinish: function() { },
* })
*
*
* 2. Read
*
* db.read({
* address: PLANARIA_ADDRESS,
* name: COLLECTION_NAME,
* filter: {
* find: FIND_FILTER,
* project: PROJECT,
* sort: SORT,
* limit: LIMIT,
* skip: SKIP,
* }
* })
*
*
* 3. Update: Delete and Insert
*
* db.update({
* address: PLANARIA_ADDRESS,
* name: COLLECTION_NAME,
* filter: {
* find: FIND_FILTER,
* project: PROJECT,
* sort: SORT,
* limit: LIMIT,
* skip: SKIP,
* },
* map: MAP_FUNCTION
* })
*
*
* 4. Delete
*
* db.delete({
* address: PLANARIA_ADDRESS,
* name: COLLECTION_NAME,
* filter: {
* find: FIND_FILTER,
* }
* })
*
***********************************/
const _create = function(o) {
let db = Manager[o.address].db
if (Array.isArray(o.data)) {
// batch insert
return new Promise(function(resolve, reject) {
let items = o
let insertMany = _.wrapCallback(function(chunk, callback) {
db.collection(o.name).insertMany(chunk, { ordered: false }, callback)
})
_(o.data).batch(1000).map(insertMany).sequence()
.errors(function(err) {
if (err.writeErrors) {
console.log("$e", JSON.stringify(err.writeErrors, null, 2))
} else {
console.log("$ Error", JSON.stringify(err, null, 2))
}
reject(err)
})
.toArray(function(x) {
console.log("batch")
resolve()
})
})
} else {
return db.collection(o.name).insertMany([o.data])
}
}
const _read = function(o) {
if (o.address && o.filter && o.filter.find && o.name) {
let db = Manager[o.address].db
let cursor = db.collection(o.name).find(o.filter.find)
if (o.filter.sort) cursor = cursor.sort(o.filter.sort)
if (o.filter.project) cursor = cursor.project(o.filter.project)
if (o.filter.skip) cursor = cursor.skip(o.filter.skip)
if (o.filter.limit) cursor = cursor.limit(o.filter.limit)
return cursor.toArray()
} else {
return new Promise(function(resolve, reject) {
reject({ error: "need address, filter, find, name" })
})
}
}
// update: delete + create
const _update = function(o) {
console.log("update", o)
return _read(o).then(function(txs) {
console.log("read", o)
let mapped = (o.map ? txs.map(o.map) : txs)
return _delete(o).then(function() {
return _create({
address: o.address,
name: o.name,
data: mapped,
})
})
})
}
const _delete = function(o) {
console.log("delete", o)
if (o.address && o.name && o.filter && o.filter.find) {
let db = Manager[o.address].db
return db.collection(o.name).deleteMany(o.filter.find)
} else {
return new Promise(function(resolve, reject) {
reject({ error: "Need address, name, filter, and find" })
})
}
}
const index = async function() {
console.log('\n\n* Indexing MongoDB...')
console.time('TotalIndex')
for(let j=0; j<GENES.length; j++) {
let gene = GENES[j]
let db = Manager[gene.address].db
if (gene.index) {
let collectionNames = Object.keys(gene.index)
for(let j=0; j<collectionNames.length; j++) {
let collectionName = collectionNames[j]
let keys = gene.index[collectionName].keys
let schema = gene.index[collectionName].schema
let uniq = gene.index[collectionName].unique
let fulltext = gene.index[collectionName].fulltext
console.log('Indexing keys...')
if (schema) {
for(let i=0; i<schema.length; i++) {
let indexItem = schema[i];
let options = null;
let keys = {};
if (typeof indexItem === 'object') {
if (indexItem.$options) {
options = indexItem.$options;
}
if (indexItem.$keys) {
keys = indexItem.$keys;
}
} else if (typeof indexItem === 'string') {
keys[indexItem] = 1;
}
console.log("KEYS = ", JSON.stringify(keys), JSON.stringify(options));
if (keys) {
console.time('Index:' + JSON.stringify(keys) + JSON.stringify(options))
try {
if (options) {
await db.collection(collectionName).createIndex(keys, options);
console.log('* Created unique index for ', keys, options);
} else {
await db.collection(collectionName).createIndex(keys);
console.log('* Created index for ', keys);
}
} catch (e) {
console.log("Error", e)
console.log("Index already exists", keys, options)
process.exit()
}
console.timeEnd('Index:' + JSON.stringify(keys) + JSON.stringify(options))
}
}
} else if (keys) {
if (Array.isArray(keys)) {
// basic
for(let i=0; i<keys.length; i++) {
let o = {}
o[keys[i]] = 1
console.time('Index:' + keys[i])
try {
if (uniq && uniq.includes(keys[i])) {
await db.collection(collectionName).createIndex(o, { unique: true })
console.log('* Created unique index for ', keys[i])
} else {
await db.collection(collectionName).createIndex(o)
console.log('* Created index for ', keys[i])
}
} catch (e) {
console.log("Index already exists", keys[i])
process.exit()
}
console.timeEnd('Index:' + keys[i])
}
} else {
// object
let k = Object.keys(keys)
for(let i=0; i<k.length; i++) {
let o = {}
let key = k[i]
o[key] = keys[key]
console.time('Index:' + key)
try {
if (uniq && uniq.includes(key)) {
await db.collection(collectionName).createIndex(o, { unique: true })
console.log('* Created unique index for ', key)
} else {
await db.collection(collectionName).createIndex(o)
console.log('* Created index for ', key)
}
} catch (e) {
console.log("Index already exists", key)
process.exit()
}
console.timeEnd('Index:' + key)
}
}
}
if (fulltext) {
console.log('Creating full text index...')
let o = {}
fulltext.forEach(function(key) {
o[key] = 'text'
})
console.time('Fulltext search for ' + collectionName, o)
try {
await db.collection(collectionName).createIndex(o, { name: 'fulltext' })
} catch (e) {
console.log("Index already exists: full text for", collectionName)
process.exit()
}
console.timeEnd('Fulltext search for ' + collectionName)
}
}
}
}
console.log('* Finished indexing MongoDB...\n\n')
console.timeEnd('TotalIndex')
}
module.exports = {
init: init, exit: exit,
instances: instances,
create: _create, read: _read, update: _update, delete: _delete,
index: index
}