-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
74 lines (67 loc) · 1.77 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
const Loki = require('lokijs')
const Lfsa = require('lokijs/src/loki-fs-structured-adapter')
let isLoaded = false
let db = null
let promiseLibrary = require('bluebird')
let initDB = (dbName, autosaveInterval) => {
try {
db = new Loki(dbName, {
adapter: new Lfsa(),
autoload: true,
autoloadCallback: () => {
isLoaded = true
},
autosave: true,
autosaveInterval: autosaveInterval || 1000
})
} catch (error) {
throw error
}
}
function getDB () {
const Promise = getPromiseLibrary()
return new Promise((resolve, reject) => {
try {
let interval = setInterval(() => {
if (isLoaded) {
clearInterval(interval)
resolve(db)
}
}, 100)
} catch (error) {
reject(error)
}
})
}
function getCollection (collectionName) {
const Promise = getPromiseLibrary()
return new Promise(async (resolve, reject) => {
try {
let database = await getDB()
let collection = database.getCollection(collectionName) ? database.getCollection(collectionName) : database.addCollection(collectionName, { clone: true, disableMeta: true }) // Creates a new DB with `clone = true` so that db records cannot be directly modified from the result-set.
resolve(collection) // This returns a Promise since this entire function is declared with the async keyword
} catch (error) {
reject(error)
}
})
}
function setPromiseLibrary (promiseLib) {
try {
promiseLibrary = promiseLib || require('bluebird')
} catch (error) {
throw error
}
}
function getPromiseLibrary () {
try {
return promiseLibrary
} catch (error) {
throw error
}
}
module.exports = {
getDB: getDB,
getCollection: getCollection,
initDB: initDB,
setPromiseLibrary: setPromiseLibrary
}