-
-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
Copy pathservice.ts
463 lines (400 loc) · 11.4 KB
/
service.ts
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import { randomBytes } from 'node:crypto'
import { getProperty } from 'dot-prop'
import inflection from 'inflection'
import { Low } from 'lowdb'
import sortOn from 'sort-on'
export type Item = Record<string, unknown>
export type Data = Record<string, Item[] | Item>
export function isItem(obj: unknown): obj is Item {
return typeof obj === 'object' && obj !== null
}
export function getNestedName(name: string): string {
return name[name.length-1] === 's' ? `${name.substring(0, name.length-1)}Id`: `${name}Id`;
}
export function isData(obj: unknown): obj is Record<string, Item[]> {
if (typeof obj !== 'object' || obj === null) {
return false
}
const data = obj as Record<string, unknown>
return Object.values(data).every(
(value) => Array.isArray(value) && value.every(isItem),
)
}
enum Condition {
lt = 'lt',
lte = 'lte',
gt = 'gt',
gte = 'gte',
ne = 'ne',
default = '',
}
function isCondition(value: string): value is Condition {
return Object.values<string>(Condition).includes(value)
}
export type PaginatedItems = {
first: number
prev: number | null
next: number | null
last: number
pages: number
items: number
data: Item[]
}
function ensureArray(arg: string | string[] = []): string[] {
return Array.isArray(arg) ? arg : [arg]
}
function embed(db: Low<Data>, name: string, item: Item, related: string): Item {
if (inflection.singularize(related) === related) {
const relatedData = db.data[inflection.pluralize(related)] as Item[]
if (!relatedData) {
return item
}
const foreignKey = `${related}Id`
const relatedItem = relatedData.find((relatedItem: Item) => {
return relatedItem['id'] === item[foreignKey]
})
return { ...item, [related]: relatedItem }
}
const relatedData: Item[] = db.data[related] as Item[]
if (!relatedData) {
return item
}
const foreignKey = `${inflection.singularize(name)}Id`
const relatedItems = relatedData.filter(
(relatedItem: Item) => relatedItem[foreignKey] === item['id'],
)
return { ...item, [related]: relatedItems }
}
function nullifyForeignKey(db: Low<Data>, name: string, id: string) {
const foreignKey = `${inflection.singularize(name)}Id`
Object.entries(db.data).forEach(([key, items]) => {
// Skip
if (key === name) return
// Nullify
if (Array.isArray(items)) {
items.forEach((item) => {
if (item[foreignKey] === id) {
item[foreignKey] = null
}
})
}
})
}
function deleteDependents(db: Low<Data>, name: string, dependents: string[]) {
const foreignKey = `${inflection.singularize(name)}Id`
Object.entries(db.data).forEach(([key, items]) => {
// Skip
if (key === name || !dependents.includes(key)) return
// Delete if foreign key is null
if (Array.isArray(items)) {
db.data[key] = items.filter((item) => item[foreignKey] !== null)
}
})
}
function randomId(): string {
return randomBytes(2).toString('hex')
}
function fixItemsIds(items: Item[]) {
items.forEach((item) => {
if (typeof item['id'] === 'number') {
item['id'] = item['id'].toString()
}
if (item['id'] === undefined) {
item['id'] = randomId()
}
})
}
// Ensure all items have an id
function fixAllItemsIds(data: Data) {
Object.values(data).forEach((value) => {
if (Array.isArray(value)) {
fixItemsIds(value)
}
})
}
export class Service {
#db: Low<Data>
constructor(db: Low<Data>) {
fixAllItemsIds(db.data)
this.#db = db
}
#get(name: string): Item[] | Item | undefined {
return this.#db.data[name]
}
has(name: string): boolean {
return Object.prototype.hasOwnProperty.call(this.#db?.data, name)
}
findById(
name: string,
id: string,
query: { _embed?: string[] | string },
): Item | undefined {
const value = this.#get(name)
if (Array.isArray(value)) {
let item = value.find((item) => item['id'] === id)
ensureArray(query._embed).forEach((related) => {
if (item !== undefined) item = embed(this.#db, name, item, related)
})
return item
}
return
}
find(
name: string,
query: {
[key: string]: unknown
_embed?: string | string[]
_sort?: string
_start?: number
_end?: number
_limit?: number
_page?: number
_per_page?: number
} = {},
): Item[] | PaginatedItems | Item | undefined {
let items = this.#get(name)
if (!Array.isArray(items)) {
return items
}
// Include
ensureArray(query._embed).forEach((related) => {
if (items !== undefined && Array.isArray(items)) {
items = items.map((item) => embed(this.#db, name, item, related))
}
})
// Return list if no query params
if (Object.keys(query).length === 0) {
return items
}
// Convert query params to conditions
const conds: [string, Condition, string | string[]][] = []
for (const [key, value] of Object.entries(query)) {
if (value === undefined || typeof value !== 'string') {
continue
}
const re = /_(lt|lte|gt|gte|ne)$/
const reArr = re.exec(key)
const op = reArr?.at(1)
if (op && isCondition(op)) {
const field = key.replace(re, '')
conds.push([field, op, value])
continue
}
if (
[
'_embed',
'_sort',
'_start',
'_end',
'_limit',
'_page',
'_per_page',
].includes(key)
) {
continue
}
conds.push([key, Condition.default, value])
}
// Loop through conditions and filter items
let filtered = items
for (const [key, op, paramValue] of conds) {
filtered = filtered.filter((item: Item) => {
if (paramValue && !Array.isArray(paramValue)) {
// https://github.com/sindresorhus/dot-prop/issues/95
const itemValue: unknown = getProperty(item, key)
switch (op) {
// item_gt=value
case Condition.gt: {
if (
!(
typeof itemValue === 'number' &&
itemValue > parseInt(paramValue)
)
) {
return false
}
break
}
// item_gte=value
case Condition.gte: {
if (
!(
typeof itemValue === 'number' &&
itemValue >= parseInt(paramValue)
)
) {
return false
}
break
}
// item_lt=value
case Condition.lt: {
if (
!(
typeof itemValue === 'number' &&
itemValue < parseInt(paramValue)
)
) {
return false
}
break
}
// item_lte=value
case Condition.lte: {
if (
!(
typeof itemValue === 'number' &&
itemValue <= parseInt(paramValue)
)
) {
return false
}
break
}
// item_ne=value
case Condition.ne: {
switch (typeof itemValue) {
case 'number':
return itemValue !== parseInt(paramValue)
case 'string':
return itemValue !== paramValue
case 'boolean':
return itemValue !== (paramValue === 'true')
}
break
}
// item=value
case Condition.default: {
switch (typeof itemValue) {
case 'number':
return itemValue === parseInt(paramValue)
case 'string':
return itemValue === paramValue
case 'boolean':
return itemValue === (paramValue === 'true')
}
}
}
}
return true
})
}
// Sort
const sort = query._sort || ''
const sorted = sortOn(filtered, sort.split(','))
// Slice
const start = query._start
const end = query._end
const limit = query._limit
if (start !== undefined) {
if (end !== undefined) {
return sorted.slice(start, end)
}
return sorted.slice(start, start + (limit || 0))
}
if (limit !== undefined) {
return sorted.slice(0, limit)
}
// Paginate
let page = query._page
const perPage = query._per_page || 10
if (page) {
const items = sorted.length
const pages = Math.ceil(items / perPage)
// Ensure page is within the valid range
page = Math.max(1, Math.min(page, pages))
const first = 1
const prev = page > 1 ? page - 1 : null
const next = page < pages ? page + 1 : null
const last = pages
const start = (page - 1) * perPage
const end = start + perPage
const data = sorted.slice(start, end)
return {
first,
prev,
next,
last,
pages,
items,
data,
}
}
return sorted.slice(start, end)
}
async create(
name: string,
data: Omit<Item, 'id'> = {},
): Promise<Item | undefined> {
const items = this.#get(name)
if (items === undefined || !Array.isArray(items)) return
const item = { id: randomId(), ...data }
items.push(item)
await this.#db.write()
return item
}
async #updateOrPatch(
name: string,
body: Item = {},
isPatch: boolean,
): Promise<Item | undefined> {
const item = this.#get(name)
if (item === undefined || Array.isArray(item)) return
const nextItem = (this.#db.data[name] = isPatch ? { item, ...body } : body)
await this.#db.write()
return nextItem
}
async #updateOrPatchById(
name: string,
id: string,
body: Item = {},
isPatch: boolean,
): Promise<Item | undefined> {
const items = this.#get(name)
if (items === undefined || !Array.isArray(items)) return
const item = items.find((item) => item['id'] === id)
if (!item) return
const nextItem = isPatch ? { ...item, ...body, id } : { ...body, id }
const index = items.indexOf(item)
items.splice(index, 1, nextItem)
await this.#db.write()
return nextItem
}
async update(name: string, body: Item = {}): Promise<Item | undefined> {
return this.#updateOrPatch(name, body, false)
}
async patch(name: string, body: Item = {}): Promise<Item | undefined> {
return this.#updateOrPatch(name, body, true)
}
async updateById(
name: string,
id: string,
body: Item = {},
): Promise<Item | undefined> {
return this.#updateOrPatchById(name, id, body, false)
}
async patchById(
name: string,
id: string,
body: Item = {},
): Promise<Item | undefined> {
return this.#updateOrPatchById(name, id, body, true)
}
async destroyById(
name: string,
id: string,
dependent?: string | string[],
): Promise<Item | undefined> {
const items = this.#get(name)
if (items === undefined || !Array.isArray(items)) return
const item = items.find((item) => item['id'] === id)
if (item === undefined) return
const index = items.indexOf(item)
items.splice(index, 1)[0]
nullifyForeignKey(this.#db, name, id)
const dependents = ensureArray(dependent)
deleteDependents(this.#db, name, dependents)
await this.#db.write()
return item
}
}