-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
230 lines (176 loc) · 6.34 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
'use strict'
const path = require('path')
const Store = require('nedb')
const helpers = require('./helpers')
const inputRecord = helpers.inputRecord
const outputRecord = helpers.outputRecord
const mapValues = helpers.mapValues
const castValue = helpers.castValue
const idKey = helpers.idKey
// By default, try to auto-compact the database every minute.
const defaultCompactionInterval = 60 * 1000
/**
* NeDB adapter.
*/
module.exports = Adapter => class NedbAdapter extends Adapter {
connect () {
const Promise = this.Promise
const recordTypes = this.recordTypes
const options = this.options
const compactionInterval = options.compactionInterval
const dbPath = options.dbPath
delete options.filename
try {
this.db = mapValues(recordTypes, (fields, type) => {
const db = new Store(Object.assign({}, options, dbPath ? {
filename: path.join(dbPath, `${type}.db`)
} : null))
db.persistence.setAutocompactionInterval(
compactionInterval ? compactionInterval : defaultCompactionInterval)
return db
})
}
catch (error) {
return Promise.reject(error)
}
return Promise.all(Object.keys(this.db).map(type =>
new Promise((resolve, reject) =>
this.db[type].loadDatabase(error => error ? reject(error) : resolve())
)))
.then(() => null)
}
disconnect () {
const Promise = this.Promise
return Promise.all(
Object.keys(this.db).map(key => new Promise(resolve => {
const db = this.db[key]
// This auto compaction interval prevents the process from exiting.
db.persistence.stopAutocompaction()
// Internal hook to NeDB's executor which will run after all other
// operations are done.
db.executor.push({ fn: resolve, arguments: [] })
}))
).then(() => null)
}
find (type, ids, options) {
// Handle no-op.
if (ids && !ids.length) return super.find()
if (!options) options = {}
const Promise = this.Promise
const recordTypes = this.recordTypes
const isArrayKey = this.keys.isArray
let query = { $and: [] }
if ('match' in options)
query.$and.push(mapValues(options.match, value =>
Array.isArray(value) ? { $in: value.map(castValue) } :
castValue(value)))
if ('exists' in options)
query.$and.push(mapValues(options.exists, (value, key) => {
if (!(key in recordTypes[type])) return void 0
if (recordTypes[type][key][isArrayKey])
return value ? { $ne: [] } : []
return value ? { $ne: null } : null
}))
if ('range' in options) {
const range = {}
query.$and.push(range)
Object.keys(options.range).forEach(key => {
if (!(key in recordTypes[type])) return
const value = options.range[key]
if (recordTypes[type][key][isArrayKey]) {
if (value[0] != null)
range[`${key}.${value[0] - 1}`] = { $exists: true }
if (value[1] != null)
range[`${key}.${value[1]}`] = { $exists: false }
return
}
range[key] = { $ne: null }
if (value[0] != null) range[key].$gte = castValue(value[0])
if (value[1] != null) range[key].$lte = castValue(value[1])
})
}
if (!query.$and.length) delete query.$and
if ('query' in options) {
const result = options.query(query)
if (result != null) query = result
}
if (ids && ids.length)
query[idKey] = { $in: ids }
// Parallelize the find method with count method.
return Promise.all([
new Promise((resolve, reject) => {
let fields
if ('fields' in options)
fields = mapValues(options.fields, value => value ? 1 : 0)
const dbCollection = this.db[type]
const find = dbCollection.find.call(dbCollection, query, fields)
if ('sort' in options)
find.sort(mapValues(options.sort, value => value ? 1 : -1))
if ('offset' in options)
find.skip(options.offset)
if ('limit' in options)
find.limit(options.limit)
find.exec((error, records) => error ? reject(error) :
resolve(records.map(outputRecord.bind(this, type)))
)
}),
new Promise((resolve, reject) =>
this.db[type].count(query, (error, count) => error ?
reject(error) : resolve(count)))
])
.then(results => {
// Set the count on the records array.
results[0].count = results[1]
return results[0]
})
}
create (type, records) {
const Promise = this.Promise
const ConflictError = this.errors.ConflictError
return new Promise((resolve, reject) =>
this.db[type].insert(
records.map(inputRecord.bind(this, type)),
(error, result) => error ?
reject(error.errorType === 'uniqueViolated' ?
new ConflictError('Duplicate key.') : error) :
resolve(result.map(outputRecord.bind(this, type)))
))
}
update (type, updates) {
const Promise = this.Promise
const primaryKey = this.keys.primary
return Promise.all(updates.map(update =>
new Promise((resolve, reject) => {
const modifiers = {}
if ('replace' in update && Object.keys(update.replace).length)
modifiers.$set = update.replace
if ('push' in update)
modifiers.$push = mapValues(update.push, value =>
Array.isArray(value) ? { $each: value } : value)
if ('pull' in update)
modifiers.$pull = mapValues(update.pull, value =>
Array.isArray(value) ? { $in: value } : value)
// Custom update operators have precedence.
Object.assign(modifiers, update.operate)
// Short circuit no-op.
if (!Object.keys(modifiers).length) {
resolve(0)
return
}
this.db[type].update({ [idKey]: update[primaryKey] },
modifiers, {}, (error, number) => error ?
reject(error) : resolve(number))
})
))
.then(numbers => numbers.reduce((accumulator, number) =>
accumulator + number, 0))
}
delete (type, ids) {
if (ids && !ids.length) return super.delete()
const Promise = this.Promise
return new Promise((resolve, reject) =>
this.db[type].remove(ids && ids.length ?
{ [idKey]: { $in: ids } } : {}, { multi: true },
(error, number) => error ? reject(error) : resolve(number)))
}
}