@@ -6,6 +6,7 @@ const Loki = require('lokijs')
66const LokiFS = Loki . LokiFsAdapter
77const LFSA = require ( 'lokijs/src/loki-fs-structured-adapter' )
88const ObjectId = require ( 'bson-objectid' )
9+ const uuidv4 = require ( 'uuid/v4' )
910
1011const MongoQuery = require ( '../mongo-query' )
1112const { promisfy } = require ( 'promisfy' )
@@ -26,14 +27,15 @@ const debug = require('debug')('bouncer.db.loki-db')
2627 */
2728module . exports = class LokiDb extends IDb {
2829
29- constructor ( { path, factory, dbAdapter, lokiOptions} ) {
30+ constructor ( { path, factory, dbAdapter, lokiOptions, useUuid } ) {
3031 super ( factory )
3132 debug ( 'constructor' )
3233 this . loki = null
3334 this . lokiOptions = lokiOptions
3435 this . path = path
3536 this . dbAdapter = dbAdapter || new LFSA ( )
3637 this . error = null
38+ this . useUuid = ( useUuid == undefined ) ? true : useUuid
3739 }
3840
3941 static get LokiLocalStorageAdapter ( ) {
@@ -142,7 +144,13 @@ module.exports = class LokiDb extends IDb {
142144 ensureId ( obj ) {
143145 let temp = { ...obj }
144146 if ( ! reach ( temp , '$meta.id' ) ) {
145- temp . $meta . id = ( new ObjectId ( ) ) . toHexString ( )
147+
148+ if ( this . useUuid ) {
149+ temp . $meta . id = uuidv4 ( )
150+ }
151+ else {
152+ temp . $meta . id = ( new ObjectId ( ) ) . toHexString ( )
153+ }
146154 }
147155
148156 let dbDoc = this . documentFromObject ( temp )
@@ -232,7 +240,19 @@ module.exports = class LokiDb extends IDb {
232240
233241 for ( let obj of docs ) {
234242 let temp = { ...obj }
235- if ( temp . _id === undefined ) { temp . _id = ( new ObjectId ( ) ) . toString ( ) ; temp . $meta . id = temp . _id ; }
243+ if ( temp . _id === undefined ) {
244+
245+ if ( this . useUuid ) {
246+ temp . _id = uuidv4 ( )
247+ }
248+ else {
249+ temp . _id = ( new ObjectId ( ) ) . toHexString ( )
250+ }
251+
252+ temp . $meta . id = temp . _id ;
253+ }
254+
255+
236256
237257 let dbDoc = this . documentFromObject ( temp )
238258
@@ -311,15 +331,16 @@ module.exports = class LokiDb extends IDb {
311331
312332 const dbDoc = collection . findAndRemove ( { '$meta.id' : obj . $meta . id } )
313333
314- debug ( 'dbDoc' , dbDoc )
315-
316- let finalObj = this . documentToObject ( dbDoc )
334+ let finalObj = {
335+ $meta : obj . $meta
336+ }
317337
318338 finalObj . $meta . removed = true
319339
320340 this . emitChange ( finalObj , 'remove' )
321341
322- debug ( 'obj' , finalObj )
342+ debug ( 'finalObj' , finalObj )
343+ debug ( 'obj' , obj )
323344
324345 await promisfy ( this . loki . saveDatabase . bind ( this . loki ) )
325346 return finalObj
0 commit comments