-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
399 lines (330 loc) · 15.5 KB
/
index.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
399
const fs = require('fs');
const path = require('path');
const bson = require('bson');
const mongoose = require('mongoose');
const LinvoDB = require('linvodb3');
const _ = require('lodash');
// See http://mongoosejs.com/docs/guide.html#toObject.
const SCHEMA_OPERATORS = [
'toObject',
'toJSON'
];
// Schemas features unsupported by LinvoDB.
const SCHEMA_UNSUPPORTED_FEATURES = [
'required',
'enum',
'validate',
// LinvoDB already defines get/set accessors which
// perform strict type validation from schema definition.
'get',
'set'
];
module.exports = {
install: function() {
function Schema(schema, options) {
for (const field in schema)
SCHEMA_UNSUPPORTED_FEATURES.forEach(feature => delete schema[field][feature]);
// Look for sub-schemas that were already processed
// to make those compatible to LinvoDB by forwarding
// their actual definition, stored under
// `schema[subSchemaField].schema`.
for (const field in schema) {
const useComplexNotation = 'type' in schema;
let fieldType = useComplexNotation ? schema[field].type : schema[field];
// ObjectId will be considered as String like _id fields
if (fieldType === mongoose.Schema.Types.ObjectId)
{
schema[field] = String;
continue;
}
if (!fieldType || !_.isArray(fieldType) || typeof fieldType !== 'object')
continue;
let fieldTypeIsArray = false;
if (_.isArray(fieldType)) {
// Preserve array of sub-schema types.
fieldType = fieldType[0];
fieldTypeIsArray = true;
}
if (!(fieldType instanceof Schema))
continue;
let normalizedFieldType = fieldTypeIsArray ? [fieldType.schema] : fieldType.schema;
if (useComplexNotation) {
schema[field].type = normalizedFieldType;
}
else {
schema[field] = {
type: normalizedFieldType
};
}
}
if (!!options) {
SCHEMA_OPERATORS.forEach(operator => {
if (!options[operator])
return;
// https://mongoosejs.com/docs/api.html#document_Document-toObject
const defaultTransform = (doc, ret, opt) => ret;
const transform = options[operator].transform || defaultTransform;
if (!transform)
return;
options[operator] = transform;
});
}
Object.assign(this, {
schema: schema,
_operators: options || {}, // See http://mongoosejs.com/docs/guide.html#toObject.
_hooks: [], // See http://mongoosejs.com/docs/middleware.html.
_virtuals: {}, // See http://mongoosejs.com/docs/2.7.x/docs/virtuals.html.
pre: function(action, callback) {
if (action === 'save')
return this._hooks.push((model) => model.on('save', (result) => callback.apply(result, [() => null])));
if (action === 'remove')
return this._hooks.push((model) => model.on('remove', (result) => callback.apply(result, [() => null])));
console.warn(`Hook action 'pre ${action}' is unimplemented.`);
},
post: function(action, callback) {
if (action === 'find')
return this._hooks.push((model) => model.on('find', (result) => callback(result, () => null)));
if (action === 'save')
return this._hooks.push((model) => model.on('updated', (result) => callback.apply(result, [() => null])));
// Note regarding "post remove" hooks:
// the "removed" event of linvodb3's Model is called
// with an array of ObjectIds of the removed documents.
// As such, the "post remove" may not be executed with
// the actual removed document, as expected by mongoose
// which is left unimplemented.
// To prevent raising an uncaught exception is the client's code,
// a warning is simply outputted.
console.warn(`Hook action 'post ${action}' is unimplemented.`);
},
virtual: function(propertyName) {
{
const schema = this;
return this._virtuals[propertyName] = {
get: function(fn) {
this._getter = fn;
return schema._virtuals[propertyName];
},
set: function(fn) {
this._setter = fn;
return schema._virtuals[propertyName];
}
};
}
},
set: function(param, value) {
// FIXME Setter for options.
}
});
};
// Override mongoose.Schema constructor.
mongoose.Schema = Schema;
mongoose.Schema.Types = Object.assign(mongoose.Schema.Types || {}, {
ObjectId: bson.ObjectID
});
mongoose.createConnection = (uri, options) => {
const defaultOptions = {
filename: 'cache'
};
// Default options.
options = options || defaultOptions;
if (!/^win/.test(process.platform)) { // !Windows
// Using pure-js medeadown store backend on Android by default.
// Comment the following line to use native LevelDB backend.
// options.storeBackend = options.storeBackend || 'medeadown';
}
const filename = options.filename;
LinvoDB.dbPath = filename || defaultOptions.filename;
const dbDirName = path.dirname(LinvoDB.dbPath);
if (!fs.existsSync(dbDirName))
fs.mkdirSync(dbDirName);
if (!!options.encode && !!options.decode) {
const codec = {
encode: options.encode,
decode: options.decode,
buffer: false,
type: 'Custom codec'
};
LinvoDB.defaults.store = Object.assign(LinvoDB.defaults.store || {}, {
valueEncoding: codec
});
}
if (!!options.storeBackend) {
LinvoDB.defaults.store = Object.assign(LinvoDB.defaults.store || {}, {
db: require(options.storeBackend)
});
}
return {
close: () => {
// FIXME Close all open models.
},
on: (event, callback) => {
// FIXME Register event handlers ('error', ...).
},
once: (event, callback) => {
// FIXME Register event handlers ('open', ...).
},
model: (name, schema) => {
// if (!('_hooks' in schema))
// schema = mongoose.schema(name, schema, options);
const modelFilename = filename || defaultOptions.filename + '/' + name + '.db';
const key = modelFilename;
const options = {
filename: modelFilename
};
const model = new LinvoDB(name, schema.schema, options);
// See http://mongoosejs.com/docs/middleware.html.
for (const hook of schema._hooks)
hook(model);
model.on('construct', function(doc) {
SCHEMA_OPERATORS.forEach(operator => {
const schemaOperator = schema._operators[operator];
if (!schemaOperator) {
doc[operator] = function() {
// Default operator.
// Nothing intended.
return this;
}
return;
}
doc[operator] = function() {
const transformedDoc = _.cloneDeep(this);
schemaOperator(this, transformedDoc);
return transformedDoc;
};
});
for (const propertyName in schema._virtuals) {
if (!!schema._virtuals[propertyName]._getter)
doc.__defineGetter__(propertyName, schema._virtuals[propertyName]._getter);
if (!!schema._virtuals[propertyName]._setter)
doc.__defineSetter__(propertyName, schema._virtuals[propertyName]._setter);
}
});
// LinvoDB does not natively support pre and post 'find'
// events, which are handled here.
const findWrapper = function(funcName) {
const fn = model[funcName];
model[funcName] = function(query, callback) {
if (!!callback && typeof callback === 'function') {
// Callback is passed to find thus invoking Cursor.exec immediately.
return fn.apply(this, [query, (error, result) => {
model.emit('find', result);
if (!!callback)
callback(error, result);
}
]);
} else {
// Callback is not directly passed to find.
// A Cursor is returned to be executed in a deferred way.
// Overriding Cursor.execFn is required to propagate 'find' event.
const cursor = fn.apply(this, [query]);
const cursorExecFn = cursor.execFn;
cursor.execFn = function(error, doc, callback) {
return cursorExecFn(error, doc, (error, result) => {
model.emit('find', result);
if (!!callback)
callback(error, result);
});
};
// Cursor.remove is unimplemented by LinvoDB.
// See http://mongoosejs.com/docs/api.html#query_Query-remove.
if (!cursor.remove) {
cursor.remove = (filter, callback) => {
if (filter && typeof filter === 'function') {
callback = filter;
filter = {};
}
return model.remove(filter, {}, callback);
};
}
return cursor;
}
};
};
findWrapper('find');
findWrapper('findById');
findWrapper('findOne');
// Override Model.insert to return result
// with MongoDB-like structure.
const insertFn = model.insert;
model.insert = function(doc, callback) {
return insertFn.apply(this, [doc, (error, result) => {
return callback(error, {
ops: [result]
});
}]);
};
// Make MongoDB-like api available through mongoose
// model.collection (ie, 'myModel.collection.insert(...)').
// 'insert' is not available from mongoose API.
if (!model.collection)
model.collection = model;
model.collection.initializeUnorderedBulkOp = function() {
// Nothing intended.
};
return model;
}
};
};
// LinvoDB does not natively support findOneAndUpdate.
LinvoDB.prototype.findOneAndUpdate = function(query, doc, options, callback) {
if (!!options && typeof options === 'function') {
callback = options;
options = undefined;
}
var self = this;
this.findOne(query, function (err, originalDocument) {
if (err)
return callback(err);
self.update(query, doc, options || {}, function(err, res) {
return callback(err, originalDocument);
});
});
};
// LinvoDB does not natively support findOneAndRemove.
LinvoDB.prototype.findOneAndRemove = function(query, options, callback) {
if (!!options && typeof options === 'function') {
callback = options;
options = undefined;
}
var self = this;
this.findOne(query, function (err, originalDocument) {
if (err)
return callback(err);
originalDocument.remove(function(err, res) {
return callback(err, res);
});
});
};
// http://mongoosejs.com/docs/api.html#model_Model.ensureIndexes
LinvoDB.prototype.ensureIndexes = function(callback) {
this.buildIndexes(!!callback && typeof callback === 'function' ? callback : () => {});
return this;
};
LinvoDB.prototype.close = function() {
// Stop the bagpipes.
// This disable any action that will be applied.
this._pipe.stop();
this._retrQueue.stop();
// See https://github.com/Level/levelup#close.
this.store.close();
};
// See http://mongoosejs.com/docs/api.html#query_Query-lean.
LinvoDB.prototype.lean = function() {
// Nothing intended.
// Results are already lean.
return this;
};
LinvoDB.Cursor.prototype.lean = function() {
// Nothing intended.
// Results are already lean.
return this;
};
LinvoDB.Cursor.prototype.select = function() {
// FIXME Implement selection (projections).
return this;
};
LinvoDB.prototype.createNewId = function() {
return new bson.ObjectID().toString();
};
}
};