-
Notifications
You must be signed in to change notification settings - Fork 0
/
mango-async.repository.ts
360 lines (331 loc) · 11 KB
/
mango-async.repository.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
import AbstractMangoRepository from '@/abstracts/mango-repo.abstract'
import logger from '@/config/logger'
import type { CreateEntityDTO, EntityDTO, PatchEntityDTO } from '@/dtos'
import type {
AggregationStages,
IMangoRepositoryAsync,
MangoCacheRepo,
QueryCriteriaOptions
} from '@/interfaces'
import type {
AggregationPipelineResult as PipelineResult,
DocumentPartial as PartialDoc,
DocumentSortingRules,
DUID,
MangoParsedUrlQuery,
MangoSearchParams,
ProjectStage,
UID
} from '@/types'
import type {
ObjectPlain,
ObjectUnknown,
OneOrMany
} from '@flex-development/tutils'
import type { Debugger } from 'debug'
/**
* @file Repositories - MangoRepositoryAsync
* @module repositories/MangoRepositoryAsync
*/
/**
* **Asynchronous** repository API for in-memory object collections.
*
* @template E - Entity
* @template U - Name of entity uid field
* @template P - Repository search parameters (query criteria and options)
* @template Q - Parsed URL query object
*
* @class
* @extends AbstractMangoRepository
* @implements {IMangoRepositoryAsync<E, U, P, Q>}
*/
export default class MangoRepositoryAsync<
E extends ObjectPlain = ObjectUnknown,
U extends string = DUID,
P extends MangoSearchParams<E> = MangoSearchParams<E>,
Q extends MangoParsedUrlQuery<E> = MangoParsedUrlQuery<E>
>
extends AbstractMangoRepository<E, U, P, Q>
implements IMangoRepositoryAsync<E, U, P, Q> {
/**
* @readonly
* @instance
* @property {Debugger} logger - Internal logger
*/
readonly logger: Debugger = logger.extend('repo').extend('async')
/**
* Runs an aggregation pipeline for `this.cache.collection`.
*
* If the cache is empty, a warning will be logged to the console instructing
* developers to call `setCache`.
*
* @async
* @param {OneOrMany<AggregationStages<E>>} [pipeline] - Aggregation stage(s)
* @return {Promise<PipelineResult<E>>} Promise containing pipeline results
*/
async aggregate(
pipeline?: OneOrMany<AggregationStages<E>>
): Promise<PipelineResult<E>> {
return super.aggregate(pipeline)
}
/**
* Clears all data from the repository.
*
* @async
* @return {Promise<true>} Promise containing `true` when data is cleared
*/
async clear(): Promise<true> {
return super.clear()
}
/**
* Creates a new entity.
*
* If the entity does is missing a uid, it will be assigned a random string
* using the [uuid][1] module.
*
* Throws a `400 BAD_REQUEST` error if schema validation is enabled and fails.
* Throws a `409 CONFLICT` error if an entity with the same uid exists.
*
* [1]: https://github.com/uuidjs/uuid
*
* @async
* @param {CreateEntityDTO<E>} dto - Data to create new entity
* @return {Promise<E>} Promise containing new entity
*/
async create(dto: CreateEntityDTO<E>): Promise<E> {
// Format dto
let data = MangoRepositoryAsync.formatCreateEntityDTO<E, U, P>(
dto,
this.cache.collection,
this.options.mingo,
this.mingo
)
// Validate new entity data
data = await this.validator.check<E>(data)
// Get name of entity uid field
const uid = this.uid()
// Get array of entities with new entity
const entities = Object.values({ ...this.cache.root, [data[uid]]: data })
// ! Set cache
await this.setCache(entities)
return data
}
/**
* Deletes a single entity or group of entities.
*
* If {@param should_exist} is `true`, a `404 NOT_FOUND` error will be thrown
* if the entity or one of the entities doesn't exist.
*
* @async
* @param {OneOrMany<UID>} [uid] - Entity uid or array of uids
* @param {boolean} [should_exist] - Throw if any entities don't exist
* @return {Promise<UID[]>} Promise containing array of uids
*/
async delete(uid?: OneOrMany<UID>, should_exist?: boolean): Promise<UID[]> {
return super.delete(uid, should_exist)
}
/**
* Executes a search against `this.cache.collection`.
*
* If the cache is empty, a warning will be logged to the console instructing
* developers to call `setCache`.
*
* @async
* @param {P} [params] - Search parameters
* @param {QueryCriteriaOptions<E>} [params.options] - Search options
* @param {ProjectStage<E>} [params.options.$project] - Fields to include
* @param {number} [params.options.limit] - Limit number of results
* @param {number} [params.options.skip] - Skips the first n entities
* @param {DocumentSortingRules<E>} [params.options.sort] - Sorting rules
* @return {Promise<PartialDoc<E, U>[]>} Promise containing search results
*/
async find(params?: P): Promise<PartialDoc<E, U>[]> {
return super.find(params)
}
/**
* Finds multiple entities by id.
*
* @async
* @param {UID[]} [uids] - Array of unique identifiers
* @param {P} [params] - Search parameters
* @param {QueryCriteriaOptions<E>} [params.options] - Search options
* @param {ProjectStage<E>} [params.options.$project] - Fields to include
* @param {number} [params.options.limit] - Limit number of results
* @param {number} [params.options.skip] - Skips the first n entities
* @param {DocumentSortingRules<E>} [params.options.sort] - Sorting rules
* @return {Promise<PartialDoc<E, U>[]>} Promise containing specified docs
*/
async findByIds(uids?: UID[], params?: P): Promise<PartialDoc<E, U>[]> {
return super.findByIds(uids, params)
}
/**
* Finds a entity by unique identifier.
*
* Returns `null` if the entity isn't found.
*
* @async
* @param {UID} uid - Unique identifier for entity
* @param {P} [params] - Search parameters
* @param {QueryCriteriaOptions<E>} [params.options] - Search options
* @param {ProjectStage<E>} [params.options.$project] - Fields to include
* @param {number} [params.options.limit] - Limit number of results
* @param {number} [params.options.skip] - Skips the first n entities
* @param {DocumentSortingRules<E>} [params.options.sort] - Sorting rules
* @return {Promise<PartialDoc<E, U> | null>} Promise containing doc or null
*/
async findOne(uid: UID, params?: P): Promise<PartialDoc<E, U> | null> {
return super.findOne(uid, params)
}
/**
* Finds a entity by unique identifier.
*
* Throws an error if the entity isn't found.
*
* @async
* @param {UID} uid - Unique identifier for entity
* @param {P} [params] - Search parameters
* @param {QueryCriteriaOptions<E>} [params.options] - Search options
* @param {ProjectStage<E>} [params.options.$project] - Fields to include
* @param {number} [params.options.limit] - Limit number of results
* @param {number} [params.options.skip] - Skips the first n entities
* @param {DocumentSortingRules<E>} [params.options.sort] - Sorting rules
* @return {Promise<PartialDoc<E, U>>} Promise containing entity
*/
async findOneOrFail(uid: UID, params?: P): Promise<PartialDoc<E, U>> {
return super.findOneOrFail(uid, params)
}
/**
* Partially updates an entity.
*
* The entity's uid field property cannot be updated.
*
* Throws an error if the entity isn't found, or if schema validation is
* enabled and fails.
*
* @async
* @param {UID} uid - Entity uid
* @param {PatchEntityDTO<E>} [dto] - Data to patch entity
* @param {string[]} [rfields] - Additional readonly fields
* @return {Promise<E>} Promise containing updated entity
*/
async patch(
uid: UID,
dto?: PatchEntityDTO<E>,
rfields?: string[]
): Promise<E> {
// Format dto
let data = MangoRepositoryAsync.formatPatchEntityDTO<E, U, P>(
uid,
dto,
rfields,
this.cache.collection,
this.options.mingo,
this.mingo
)
// Validate dto
data = await this.validator.check<E>(data)
// ! Set cache
await this.setCache(Object.values({ ...this.cache.root, [uid]: data }))
return data
}
/**
* Queries `this.cache.collection`.
*
* If the cache is empty, a warning will be logged to the console instructing
* developers to call `setCache`.
*
* @async
* @param {Q | string} [query] - Document query object or string
* @return {Promise<PartialDoc<E, U>[]>} Promise containing search results
*/
async query(query?: Q | string): Promise<PartialDoc<E, U>[]> {
return super.query(query)
}
/**
* Queries multiple entities by unique identifier.
*
* @async
* @param {UID[]} [uids] - Array of unique identifiers
* @param {Q | string} [query] - Document query object or string
* @return {Promise<PartialDoc<E, U>[]>} Promise containing specified docs
*/
async queryByIds(
uids?: UID[],
query?: Q | string
): Promise<PartialDoc<E, U>[]> {
return super.queryByIds(uids, query)
}
/**
* Queries a entity by unique identifier.
*
* Returns `null` if the entity isn't found.
*
* @async
* @param {UID} uid - Unique identifier for entity
* @param {Q | string} [query] - Document query object or string
* @return {Promise<PartialDoc<E, U> | null>} Promise containing doc or null
*/
async queryOne(
uid: UID,
query?: Q | string
): Promise<PartialDoc<E, U> | null> {
return super.queryOne(uid, query)
}
/**
* Queries a entity by id.
*
* Throws an error if the entity isn't found.
*
* @async
* @param {UID} uid - Unique identifier for entity
* @param {Q | string} [query] - Document query object or string
* @return {Promise<PartialDoc<E, U>>} Promise containing entity
*/
async queryOneOrFail(
uid: UID,
query?: Q | string
): Promise<PartialDoc<E, U>> {
return super.queryOneOrFail(uid, query)
}
/**
* Creates or updates a single entity or array of entities.
*
* If any entity already exists, it will be patched.
* If any entity does not exist in the database, it will be inserted.
*
* @async
* @param {OneOrMany<EntityDTO<E>>} [dto] - Entities to upsert
* @return {Promise<E[]>} Promise containing new or updated entities
*/
async save(dto: OneOrMany<EntityDTO<E>> = []): Promise<E[]> {
/**
* Creates or updates a single entity.
*
* If the entity already exists in the database, it will be updated.
* If the entity does not exist in the database, it will be inserted.
*
* @async
* @param {EntityDTO<E>} dto - Data to upsert entity
* @return {Promise<E>} Promise containing new or updated entiy
*/
const upsert = async (dto: EntityDTO<E>): Promise<E> => {
const uid = dto[this.uid()] as UID
const exists = await this.findOne(uid)
if (!exists) return await this.create(dto as CreateEntityDTO<E>)
return await this.patch(uid, dto as PatchEntityDTO<E>)
}
// Convert into array of DTOs
const dtos = Array.isArray(dto) ? dto : [dto]
// @ts-expect-error performing upsert
return await Promise.all(dtos.map(async d => upsert(d)))
}
/**
* Updates the repository's the data cache.
*
* @param {E[]} [collection] - Entities to insert into cache
* @return {Promise<MangoCacheRepo<E>>} Copy of updated repository cache
*/
async setCache(collection?: E[]): Promise<MangoCacheRepo<E>> {
return super.setCache(collection)
}
}