forked from feathersjs-ecosystem/feathers-objection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
425 lines (358 loc) · 10.2 KB
/
index.js
File metadata and controls
425 lines (358 loc) · 10.2 KB
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import Proto from 'uberproto'
import filter from 'feathers-query-filters'
import isPlainObject from 'is-plain-object'
import errorHandler from './error-handler'
import { errors } from 'feathers-errors'
const METHODS = {
$or: 'orWhere',
$ne: 'whereNot',
$in: 'whereIn',
$nin: 'whereNotIn'
}
const OPERATORS = {
$lt: '<',
$lte: '<=',
$gt: '>',
$gte: '>=',
$like: 'like'
}
/**
* Class representing an feathers adapter for objection.js ORM.
* @param {object} options
* @param {string} [id='id'] - database id field
* @param {object} options.model - an objection model
* @param {object} [options.paginate]
* @param {string} [allowedEager] - Objection eager loading string.
*/
class Service {
constructor (options) {
if (!options) {
throw new Error('Objection options have to be provided')
}
if (!options.model) {
throw new Error('You must provide an Objection Model')
}
this.options = options || {}
this.id = options.id || 'id'
this.paginate = options.paginate || {}
this.events = options.events || []
this.Model = options.model
this.allowedEager = options.allowedEager || '[]'
this.namedEagerFilters = options.namedEagerFilters
this.eagerFilters = options.eagerFilters
}
extend (obj) {
return Proto.extend(obj, this)
}
/**
* Maps a feathers query to the objection/knex schema builder functions.
* @param query - a query object. i.e. { type: 'fish', age: { $lte: 5 }
* @param params
* @param parentKey
*/
objectify (query, params, parentKey) {
// Delete $eager
if (params.$eager) {
delete params.$eager;
}
// Delete $joinEager
if (params.$joinEager) {
delete params.$joinEager;
}
Object.keys(params || {}).forEach(key => {
const value = params[key]
if (isPlainObject(value)) {
return this.objectify(query, value, key)
}
const column = parentKey || key
const method = METHODS[key]
const operator = OPERATORS[key] || '='
if (method) {
if (key === '$or') {
const self = this
return value.forEach(condition => {
query[method](function () {
self.objectify(this, condition)
})
})
}
return query[method].call(query, column, value) // eslint-disable-line no-useless-call
}
return query.where(column, operator, value)
})
}
createQuery (paramsQuery = {}) {
const { filters, query } = filter(paramsQuery)
let q = this.Model.query()
.skipUndefined()
.allowEager(this.allowedEager)
// $eager for objection eager queries
let $eager
let $joinEager
if (query && query.$eager) {
$eager = query.$eager
delete query.$eager
q.eager($eager, this.namedEagerFilters)
}
if (query && query.$joinEager) {
$joinEager = query.$joinEager
delete query.$joinEager
q
.eagerAlgorithm(this.Model.JoinEagerAlgorithm)
.eager($joinEager, this.namedEagerFilters)
}
// $select uses a specific find syntax, so it has to come first.
if (filters.$select) {
q = this.Model.query()
.skipUndefined()
.allowEager(this.allowedEager)
.select(...filters.$select.concat(this.id))
if ($eager) {
q.eager($eager, this.namedEagerFilters)
} else if ($joinEager) {
q
.eagerAlgorithm(this.Model.JoinEagerAlgorithm)
.eager($joinEager, this.namedEagerFilters)
}
// .joinEager($joinEager, this.namedEagerFilters)
}
// apply eager filters if specified
if (this.eagerFilters) {
const eagerFilters = this.eagerFilters
if (Array.isArray(eagerFilters)) {
for (var eagerFilter of eagerFilters) {
q.filterEager(eagerFilter.expression, eagerFilter.filter)
}
} else {
q.filterEager(eagerFilters.expression, eagerFilters.filter)
}
}
// build up the knex query out of the query params
this.objectify(q, query)
if (filters.$sort) {
Object.keys(filters.$sort).forEach(key => {
q = q.orderBy(key, filters.$sort[key] === 1 ? 'asc' : 'desc')
})
}
return q
}
_find (params, count, getFilter = filter) {
const { filters, query } = getFilter(params.query || {})
const q = params.objection || this.createQuery(params.query)
// Handle $limit
if (filters.$limit) {
q.limit(filters.$limit)
}
// Handle $skip
if (filters.$skip) {
q.offset(filters.$skip)
}
let executeQuery = total => {
return q.then(data => {
return {
total,
limit: filters.$limit,
skip: filters.$skip || 0,
data
}
})
}
if (filters.$limit === 0) {
executeQuery = total => {
return Promise.resolve({
total,
limit: filters.$limit,
skip: filters.$skip || 0,
data: []
})
}
}
if (count) {
let countQuery = this.Model.query()
.skipUndefined()
.count(`${this.id} as total`)
this.objectify(countQuery, query)
return countQuery
.then(count => parseInt(count[0].total, 10))
.then(executeQuery)
}
return executeQuery().catch(errorHandler)
}
/**
* `find` service function for objection.
* @param params
*/
find (params) {
const paginate =
params && typeof params.paginate !== 'undefined'
? params.paginate
: this.paginate
const result = this._find(params, !!paginate.default, query =>
filter(query, paginate)
)
if (!paginate.default) {
return result.then(page => page.data)
}
return result
}
_get (id, params) {
const query = Object.assign({}, params.query)
query[this.id] = id
return this._find(Object.assign({}, params, { query }))
.then(page => {
if (page.data.length !== 1) {
throw new errors.NotFound(`No record found for id '${id}'`)
}
return page.data[0]
})
.catch(errorHandler)
}
/**
* `get` service function for objection.
* @param {...object} args
* @return {Promise} - promise containing the data being retrieved
*/
get (...args) {
return this._get(...args)
}
_create (data, params) {
return this.Model.query()
.insert(data, this.id)
.then(row => {
const id =
typeof data[this.id] !== 'undefined' ? data[this.id] : row[this.id]
return this._get(id, params)
})
.catch(errorHandler)
}
/**
* `create` service function for objection.
* @param {object} data
* @param {object} params
*/
create (data, params) {
if (Array.isArray(data)) {
return Promise.all(data.map(current => this._create(current, params)))
}
return this._create(data, params)
}
/**
* `update` service function for objection.
* @param id
* @param data
* @param params
*/
update (id, data, params) {
if (Array.isArray(data)) {
return Promise.reject(
'Not replacing multiple records. Did you mean `patch`?'
)
}
// NOTE (EK): First fetch the old record so
// that we can fill any existing keys that the
// client isn't updating with null;
return this._get(id, params)
.then(oldData => {
let newObject = {}
for (var key of Object.keys(oldData)) {
if (data[key] === undefined) {
newObject[key] = null
} else {
newObject[key] = data[key]
}
}
// NOTE (EK): Delete id field so we don't update it
delete newObject[this.id]
return this.Model.query()
.where(this.id, id)
.update(newObject)
.then(() => {
// NOTE (EK): Restore the id field so we can return it to the client
newObject[this.id] = id
return newObject
})
})
.catch(errorHandler)
}
/**
* `patch` service function for objection.
* @param id
* @param data
* @param params
*/
patch (id, raw, params) {
const query = filter(params.query || {}).query
const data = Object.assign({}, raw)
const mapIds = page => page.data.map(current => current[this.id])
// By default we will just query for the one id. For multi patch
// we create a list of the ids of all items that will be changed
// to re-query them after the update
const ids =
id === null ? this._find(params).then(mapIds) : Promise.resolve([id])
if (id !== null) {
query[this.id] = id
}
let q = this.Model.query()
this.objectify(q, query)
delete data[this.id]
return ids
.then(idList => {
// Create a new query that re-queries all ids that
// were originally changed
const findParams = Object.assign({}, params, {
query: {
[this.id]: { $in: idList },
$select: params.query && params.query.$select
}
})
return q.patch(data).then(() => {
return this._find(findParams).then(page => {
const items = page.data
if (id !== null) {
if (items.length === 1) {
return items[0]
} else {
throw new errors.NotFound(`No record found for id '${id}'`)
}
}
return items
})
})
})
.catch(errorHandler)
}
/**
* `remove` service function for objection.
* @param id
* @param params
*/
remove (id, params) {
params.query = params.query || {}
// NOTE (EK): First fetch the record so that we can return
// it when we delete it.
if (id !== null) {
params.query[this.id] = id
}
return this._find(params)
.then(page => {
const items = page.data
const query = this.Model.query()
this.objectify(query, params.query)
return query.delete().then(() => {
if (id !== null) {
if (items.length === 1) {
return items[0]
} else {
throw new errors.NotFound(`No record found for id '${id}'`)
}
}
return items
})
})
.catch(errorHandler)
}
}
export default function init (options) {
return new Service(options)
}
init.Service = Service