@point-hub/papi 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/lib/src/app.d.ts +3 -0
  2. package/lib/src/app.d.ts.map +1 -0
  3. package/lib/src/app.spec.d.ts +2 -0
  4. package/lib/src/app.spec.d.ts.map +1 -0
  5. package/lib/src/console/commands/make-command/index.command.d.ts +6 -0
  6. package/lib/src/console/commands/make-command/index.command.d.ts.map +1 -0
  7. package/lib/src/console/commands/make-command/index.spec.d.ts +2 -0
  8. package/lib/src/console/commands/make-command/index.spec.d.ts.map +1 -0
  9. package/lib/src/console/commands/make-middleware/index.command.d.ts +8 -0
  10. package/lib/src/console/commands/make-middleware/index.command.d.ts.map +1 -0
  11. package/lib/src/console/commands/make-middleware/index.spec.d.ts +2 -0
  12. package/lib/src/console/commands/make-middleware/index.spec.d.ts.map +1 -0
  13. package/lib/src/console/index.d.ts +13 -0
  14. package/lib/src/console/index.d.ts.map +1 -0
  15. package/lib/src/console/index.spec.d.ts +2 -0
  16. package/lib/src/console/index.spec.d.ts.map +1 -0
  17. package/lib/src/database/connection.d.ts +33 -0
  18. package/lib/src/database/connection.d.ts.map +1 -0
  19. package/lib/src/database/mongodb/connection.d.ts +38 -0
  20. package/lib/src/database/mongodb/connection.d.ts.map +1 -0
  21. package/lib/src/database/mongodb/mongodb-error-handler.d.ts +10 -0
  22. package/lib/src/database/mongodb/mongodb-error-handler.d.ts.map +1 -0
  23. package/lib/src/database/mongodb/mongodb-helper.d.ts +36 -0
  24. package/lib/src/database/mongodb/mongodb-helper.d.ts.map +1 -0
  25. package/lib/src/database/mongodb/mongodb-querystring.d.ts +82 -0
  26. package/lib/src/database/mongodb/mongodb-querystring.d.ts.map +1 -0
  27. package/lib/src/database/mongodb/mongodb-querystring.spec.d.ts +2 -0
  28. package/lib/src/database/mongodb/mongodb-querystring.spec.d.ts.map +1 -0
  29. package/lib/src/index.d.ts +39 -0
  30. package/lib/src/index.d.ts.map +1 -0
  31. package/lib/src/interfaces/types.d.ts +112 -0
  32. package/lib/src/interfaces/types.d.ts.map +1 -0
  33. package/lib/src/server.d.ts +16 -0
  34. package/lib/src/server.d.ts.map +1 -0
  35. package/lib/src/server.spec.d.ts +2 -0
  36. package/lib/src/server.spec.d.ts.map +1 -0
  37. package/lib/stub/command/index.command.d.ts +6 -0
  38. package/lib/stub/command/index.command.d.ts.map +1 -0
  39. package/lib/stub/command/index.spec.d.ts +2 -0
  40. package/lib/stub/command/index.spec.d.ts.map +1 -0
  41. package/lib/stub/middleware/configurable.middleware.d.ts +3 -0
  42. package/lib/stub/middleware/configurable.middleware.d.ts.map +1 -0
  43. package/lib/stub/middleware/configurable.spec.d.ts +2 -0
  44. package/lib/stub/middleware/configurable.spec.d.ts.map +1 -0
  45. package/lib/stub/middleware/new.middleware.d.ts +3 -0
  46. package/lib/stub/middleware/new.middleware.d.ts.map +1 -0
  47. package/lib/stub/middleware/new.spec.d.ts +2 -0
  48. package/lib/stub/middleware/new.spec.d.ts.map +1 -0
  49. package/package.json +4 -5
  50. package/lib/index.d.ts +0 -318
  51. package/lib/index.tsbuildinfo +0 -1
  52. package/src/app.spec.ts +0 -8
  53. package/src/app.ts +0 -13
  54. package/src/console/commands/make-command/index.command.ts +0 -52
  55. package/src/console/commands/make-command/index.spec.ts +0 -58
  56. package/src/console/commands/make-middleware/index.command.ts +0 -86
  57. package/src/console/commands/make-middleware/index.spec.ts +0 -73
  58. package/src/console/index.spec.ts +0 -14
  59. package/src/console/index.ts +0 -23
  60. package/src/database/connection.ts +0 -78
  61. package/src/database/mongodb/connection.ts +0 -339
  62. package/src/database/mongodb/mongodb-error-handler.ts +0 -63
  63. package/src/database/mongodb/mongodb-helper.ts +0 -109
  64. package/src/database/mongodb/mongodb-querystring.spec.ts +0 -80
  65. package/src/database/mongodb/mongodb-querystring.ts +0 -143
  66. package/src/index.ts +0 -42
  67. package/src/server.spec.ts +0 -68
  68. package/src/server.ts +0 -49
  69. package/src/types/controller.d.ts +0 -18
  70. package/src/types/database.d.ts +0 -104
  71. package/src/types/use-case.d.ts +0 -3
@@ -1,86 +0,0 @@
1
- import { BaseCommand, Color } from '@point-hub/express-cli'
2
- import { kebabCase, pascalCase } from '@point-hub/express-utils'
3
- import fs from 'fs'
4
- import path from 'path'
5
-
6
- import { stubDir } from '../../../index'
7
-
8
- export default class MakeMiddleware extends BaseCommand {
9
- constructor() {
10
- super({
11
- name: 'make:middleware',
12
- description: 'Make a new middleware',
13
- summary: 'Make a new middleware',
14
- arguments: [
15
- {
16
- name: 'name',
17
- description: 'Name of middleware',
18
- },
19
- ],
20
- options: [
21
- {
22
- type: 'boolean',
23
- flag: '--configurable',
24
- shorthand: '-c',
25
- description: 'Export a function which accepts an options',
26
- },
27
- ],
28
- })
29
- }
30
-
31
- async handle(): Promise<void> {
32
- // Check if middleware directory is already exists
33
- if (fs.existsSync(`${process.cwd()}/src/middleware/${kebabCase(this.args.name)}`)) {
34
- console.error(Color.red('Middleware directory is exists'))
35
- return
36
- }
37
-
38
- // Create middleware directory
39
- fs.mkdirSync(`${process.cwd()}/src/middleware/${kebabCase(this.args.name)}`, { recursive: true })
40
-
41
- // Copy middleware
42
- if (this.opts['--configurable']) {
43
- this.copyConfigureableMiddleware()
44
- } else {
45
- this.copyMiddleware()
46
- }
47
- }
48
-
49
- private copyMiddleware() {
50
- // Copy middleware file
51
- const stubMiddleware = fs
52
- .readFileSync(path.resolve(stubDir, './middleware/new.middleware.ts'))
53
- .toString()
54
- .replace('NewMiddleware', `${pascalCase(this.args.name)}Middleware`)
55
- fs.writeFileSync(`${process.cwd()}/src/middleware/${kebabCase(this.args.name)}/index.middleware.ts`, stubMiddleware)
56
-
57
- // Copy test file
58
- const stubTest = fs
59
- .readFileSync(path.resolve(stubDir, './middleware/new.spec.ts'))
60
- .toString()
61
- .replace('new.middleware.ts', `index.middleware.ts`)
62
- fs.writeFileSync(`${process.cwd()}/src/middleware/${kebabCase(this.args.name)}/index.spec.ts`, stubTest)
63
-
64
- console.info(`src/middleware/${kebabCase(this.args.name)}/index.middleware.ts`, 'has been created')
65
- console.info(`src/middleware/${kebabCase(this.args.name)}/index.spec.ts`, 'has been created')
66
- }
67
-
68
- private copyConfigureableMiddleware() {
69
- // Copy middleware file
70
- const stubMiddleware = fs
71
- .readFileSync(path.resolve(stubDir, './middleware/configurable.middleware.ts'))
72
- .toString()
73
- .replace('NewMiddleware', `${pascalCase(this.args.name)}Middleware`)
74
- fs.writeFileSync(`${process.cwd()}/src/middleware/${kebabCase(this.args.name)}/index.middleware.ts`, stubMiddleware)
75
-
76
- // Copy test file
77
- const stubTest = fs
78
- .readFileSync(path.resolve(stubDir, './middleware/configurable.spec.ts'))
79
- .toString()
80
- .replace('configurable.middleware.ts', `index.middleware.ts`)
81
- fs.writeFileSync(`${process.cwd()}/src/middleware/${kebabCase(this.args.name)}/index.spec.ts`, stubTest)
82
-
83
- console.info(`src/middleware/${kebabCase(this.args.name)}/index.middleware.ts`, 'has been created')
84
- console.info(`src/middleware/${kebabCase(this.args.name)}/index.spec.ts`, 'has been created')
85
- }
86
- }
@@ -1,73 +0,0 @@
1
- import { Color } from '@point-hub/express-cli'
2
- import { beforeAll, describe, expect, it, spyOn } from 'bun:test'
3
- import crypto from 'crypto'
4
- import fs from 'fs'
5
- import shell from 'shelljs'
6
-
7
- import MakeMiddlewareCommand from './index.command'
8
-
9
- const dir = 'src/middleware'
10
-
11
- function generateRandomName() {
12
- let exists = true
13
- let name = 'test'
14
- while (exists) {
15
- name = `test-${crypto.randomBytes(4).toString('hex')}`
16
- exists = fs.existsSync(`${dir}/${name}`)
17
- }
18
- return name
19
- }
20
-
21
- describe('make:middleware', () => {
22
- beforeAll(() => {
23
- spyOn(console, 'error').mockImplementation(() => '')
24
- spyOn(console, 'info').mockImplementation(() => '')
25
- })
26
- it('should create new middleware', async () => {
27
- const makeMiddlewareCommand = new MakeMiddlewareCommand()
28
- makeMiddlewareCommand.args = {
29
- name: generateRandomName(),
30
- }
31
- const spy = spyOn(makeMiddlewareCommand, 'handle')
32
- await makeMiddlewareCommand.handle()
33
-
34
- shell.rm('-rf', `${dir}/${makeMiddlewareCommand.args.name}`)
35
-
36
- expect(spy).toHaveBeenCalled()
37
- })
38
-
39
- it('should create new configureable middleware', async () => {
40
- const makeMiddlewareCommand = new MakeMiddlewareCommand()
41
- makeMiddlewareCommand.args = {
42
- name: generateRandomName(),
43
- }
44
- makeMiddlewareCommand.opts = {
45
- '--configurable': true,
46
- }
47
- const spy = spyOn(makeMiddlewareCommand, 'handle')
48
- await makeMiddlewareCommand.handle()
49
-
50
- shell.rm('-rf', `${dir}/${makeMiddlewareCommand.args.name}`)
51
-
52
- expect(spy).toHaveBeenCalled()
53
- })
54
-
55
- it("should return error 'middleware directory exists'", async () => {
56
- const makeMiddlewareCommand = new MakeMiddlewareCommand()
57
- makeMiddlewareCommand.args = {
58
- name: generateRandomName(),
59
- }
60
- const spy = spyOn(makeMiddlewareCommand, 'handle')
61
-
62
- // first attempt it will create new middleware
63
- await makeMiddlewareCommand.handle()
64
- // second attempt it should return error because middleware directory exists
65
- await makeMiddlewareCommand.handle()
66
-
67
- shell.rm('-rf', `${dir}/${makeMiddlewareCommand.args.name}`)
68
-
69
- expect(console.error).toHaveBeenCalled()
70
- expect(console.error).toHaveBeenCalledWith(Color.red('Middleware directory is exists'))
71
- expect(spy).toHaveBeenCalled()
72
- })
73
- })
@@ -1,14 +0,0 @@
1
- import { ExpressCli } from '@point-hub/express-cli'
2
- import { expect, it } from 'bun:test'
3
-
4
- import { ConsoleKernel } from './index'
5
-
6
- it('express cli to be defined', async () => {
7
- const cli = new ExpressCli('cli', '1.0.0')
8
-
9
- const kernel = new ConsoleKernel(cli)
10
- await kernel.register()
11
-
12
- expect(cli).toBeDefined()
13
- expect(cli).toBeInstanceOf(ExpressCli)
14
- })
@@ -1,23 +0,0 @@
1
- import { ExpressCli } from '@point-hub/express-cli'
2
-
3
- import MakeCommand from './commands/make-command/index.command'
4
- import MakeMiddleware from './commands/make-middleware/index.command'
5
-
6
- export class ConsoleKernel {
7
- private command: ExpressCli
8
-
9
- constructor(command: ExpressCli) {
10
- this.command = command
11
- }
12
-
13
- /**
14
- * Register the commands for the application.
15
- *
16
- * @example
17
- * this.command.register(new ExampleCommand());
18
- */
19
- async register() {
20
- this.command.register(new MakeCommand())
21
- this.command.register(new MakeMiddleware())
22
- }
23
- }
@@ -1,78 +0,0 @@
1
- export class DatabaseConnection implements IDatabase {
2
- session: unknown
3
- constructor(public adapter: IDatabase) {}
4
- public async open(): Promise<void> {
5
- await this.adapter.open()
6
- }
7
- public async close(): Promise<void> {
8
- await this.adapter.close()
9
- }
10
- public database(name: string): this {
11
- this.adapter.database(name)
12
- return this
13
- }
14
- public collection(name: string): this {
15
- this.adapter.collection(name)
16
- return this
17
- }
18
- public async listCollections(): Promise<{ name: string }[]> {
19
- return this.adapter.listCollections()
20
- }
21
- public startSession() {
22
- return this.adapter.startSession()
23
- }
24
- public async endSession() {
25
- await this.adapter.endSession()
26
- }
27
- public startTransaction() {
28
- this.adapter.startTransaction()
29
- }
30
- public async commitTransaction() {
31
- await this.adapter.commitTransaction()
32
- }
33
- public async abortTransaction() {
34
- await this.adapter.abortTransaction()
35
- }
36
- public async createIndex(name: string, spec: unknown, options?: unknown) {
37
- await this.adapter.createIndex(name, spec, options)
38
- }
39
- public async createCollection(name: string, options?: unknown) {
40
- await this.adapter.createCollection(name, options)
41
- }
42
- public async dropCollection(name: string, options?: unknown) {
43
- await this.adapter.dropCollection(name, options)
44
- }
45
- public async updateSchema(name: string, schema: unknown) {
46
- await this.adapter.updateSchema(name, schema)
47
- }
48
- public async create(document: IDocument, options?: unknown): Promise<ICreateOutput> {
49
- return await this.adapter.create(document, options)
50
- }
51
- public async createMany(documents: IDocument[], options?: unknown): Promise<ICreateManyOutput> {
52
- return await this.adapter.createMany(documents, options)
53
- }
54
- public async retrieveAll(query: IQuery, options?: unknown): Promise<IRetrieveAllOutput> {
55
- return await this.adapter.retrieveAll(query, options)
56
- }
57
- public async retrieve(_id: string, options?: unknown): Promise<IRetrieveOutput> {
58
- return await this.adapter.retrieve(_id, options)
59
- }
60
- public async update(_id: string, document: IDocument, options?: unknown): Promise<IUpdateOutput> {
61
- return await this.adapter.update(_id, document, options)
62
- }
63
- public async updateMany(filter: IDocument, document: IDocument, options?: unknown): Promise<IUpdateManyOutput> {
64
- return await this.adapter.updateMany(filter, document, options)
65
- }
66
- public async delete(_id: string, options?: unknown): Promise<IDeleteOutput> {
67
- return await this.adapter.delete(_id, options)
68
- }
69
- public async deleteMany(_ids: string[], options?: unknown): Promise<IDeleteManyOutput> {
70
- return await this.adapter.deleteMany(_ids, options)
71
- }
72
- public async deleteAll(options?: unknown): Promise<IDeleteManyOutput> {
73
- return await this.adapter.deleteAll(options)
74
- }
75
- public async aggregate(pipeline: IPipeline[], query: IQuery, options?: unknown): Promise<IAggregateOutput> {
76
- return await this.adapter.aggregate(pipeline, query, options)
77
- }
78
- }
@@ -1,339 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
- import type {
3
- AggregateOptions,
4
- BulkWriteOptions,
5
- ClientSession,
6
- Collection,
7
- CollectionOptions,
8
- CreateIndexesOptions,
9
- Db,
10
- DbOptions,
11
- DeleteOptions,
12
- FindOptions,
13
- IndexSpecification,
14
- InsertOneOptions,
15
- MongoClientOptions,
16
- UpdateOptions,
17
- } from 'mongodb'
18
- import { MongoClient, ObjectId } from 'mongodb'
19
-
20
- import { MongoDBHelper } from './mongodb-helper'
21
- import Querystring from './mongodb-querystring'
22
-
23
- export class MongoDBConnection implements IDatabase {
24
- public client: MongoClient
25
- public _database: Db | undefined
26
- public _collection: Collection | undefined
27
- public session: ClientSession | undefined
28
-
29
- constructor(
30
- connectionString: string,
31
- public databaseName: string,
32
- ) {
33
- const options: MongoClientOptions = {}
34
-
35
- this.client = new MongoClient(connectionString, options)
36
- this.database(databaseName)
37
- }
38
-
39
- public async open() {
40
- await this.client.connect()
41
- }
42
-
43
- public async close() {
44
- await this.client.close()
45
- }
46
-
47
- public database(name: string, options?: DbOptions) {
48
- this._database = this.client.db(name, options)
49
- return this
50
- }
51
-
52
- public collection(name: string, options?: CollectionOptions) {
53
- if (!this._database) {
54
- throw new Error('Database not found')
55
- }
56
-
57
- this._collection = this._database.collection(name, options)
58
- return this
59
- }
60
-
61
- public async listCollections(): Promise<{ name: string }[]> {
62
- if (!this._database) {
63
- throw new Error('Database not found')
64
- }
65
-
66
- return await this._database.listCollections().toArray()
67
- }
68
-
69
- public async createIndex(name: string, spec: IndexSpecification, options: CreateIndexesOptions): Promise<void> {
70
- if (!this._database) {
71
- throw new Error('Database not found')
72
- }
73
-
74
- await this._database.createIndex(name, spec, options)
75
- }
76
-
77
- public async updateSchema(name: string, schema: unknown): Promise<void> {
78
- if (!this._database) {
79
- throw new Error('Database not found')
80
- }
81
-
82
- await this._database.command({
83
- collMod: name,
84
- validator: {
85
- $jsonSchema: schema,
86
- },
87
- })
88
- }
89
-
90
- public async createCollection(name: string, options: any): Promise<void> {
91
- if (!this._database) {
92
- throw new Error('Database not found')
93
- }
94
-
95
- await this._database.createCollection(name, options)
96
- }
97
-
98
- public async dropCollection(name: string, options: any): Promise<void> {
99
- if (!this._database) {
100
- throw new Error('Database not found')
101
- }
102
-
103
- await this._database.dropCollection(name, options)
104
- }
105
-
106
- public startSession() {
107
- this.session = this.client.startSession()
108
- return this.session
109
- }
110
-
111
- public async endSession() {
112
- await this.session?.endSession()
113
- }
114
-
115
- public startTransaction() {
116
- this.session?.startTransaction()
117
- }
118
-
119
- public async commitTransaction() {
120
- await this.session?.commitTransaction()
121
- }
122
-
123
- public async abortTransaction() {
124
- await this.session?.abortTransaction()
125
- }
126
-
127
- public async create(document: IDocument, options?: unknown): Promise<ICreateOutput> {
128
- if (!this._collection) {
129
- throw new Error('Collection not found')
130
- }
131
-
132
- const createOptions = options as InsertOneOptions
133
-
134
- const response = await this._collection.insertOne(document, createOptions)
135
-
136
- return {
137
- insertedId: response.insertedId.toString(),
138
- }
139
- }
140
-
141
- public async createMany(documents: IDocument[], options?: unknown): Promise<ICreateManyOutput> {
142
- if (!this._collection) {
143
- throw new Error('Collection not found')
144
- }
145
-
146
- const createManyOptions = options as BulkWriteOptions
147
-
148
- const response = await this._collection.insertMany(documents, createManyOptions)
149
-
150
- // convert array of object to array of string
151
- const insertedIds: string[] = []
152
- Object.values(response.insertedIds).forEach((val) => {
153
- insertedIds.push(val.toString())
154
- })
155
-
156
- return {
157
- insertedIds: insertedIds,
158
- insertedCount: response.insertedCount,
159
- }
160
- }
161
-
162
- public async retrieveAll(query: IQuery, options?: any): Promise<IRetrieveAllOutput> {
163
- if (!this._collection) {
164
- throw new Error('Collection not found')
165
- }
166
-
167
- const retrieveOptions = options as FindOptions
168
-
169
- const cursor = this._collection
170
- .find(MongoDBHelper.stringToObjectId(query.filter ?? {}), retrieveOptions)
171
- .limit(Querystring.limit(query.pageSize))
172
- .skip(Querystring.skip(Querystring.page(query.page), Querystring.limit(query.pageSize)))
173
-
174
- if (query.sort && Querystring.sort(query.sort)) {
175
- cursor.sort(Querystring.sort(query.sort))
176
- }
177
-
178
- if (Querystring.fields(query.fields, query.excludeFields)) {
179
- cursor.project(Querystring.fields(query.fields, query.excludeFields))
180
- }
181
- const result = await cursor.toArray()
182
-
183
- const totalDocument = await this._collection.countDocuments(query.filter ?? {}, retrieveOptions)
184
-
185
- return {
186
- data: MongoDBHelper.objectIdToString(result) as unknown[] as IRetrieveOutput[],
187
- pagination: {
188
- page: Querystring.page(query.page),
189
- pageCount: Math.ceil(totalDocument / Querystring.limit(query.pageSize)),
190
- pageSize: Querystring.limit(query.pageSize),
191
- totalDocument,
192
- },
193
- }
194
- }
195
-
196
- public async retrieve(_id: string, options?: any): Promise<IRetrieveOutput> {
197
- if (!this._collection) {
198
- throw new Error('Collection not found')
199
- }
200
-
201
- const retrieveOptions = options as FindOptions
202
-
203
- const result = await this._collection.findOne(
204
- {
205
- _id: new ObjectId(_id),
206
- },
207
- retrieveOptions,
208
- )
209
-
210
- return MongoDBHelper.objectIdToString(result)
211
- }
212
-
213
- public async update(_id: string, document: IDocument, options?: any): Promise<IUpdateOutput> {
214
- if (!this._collection) {
215
- throw new Error('Collection not found')
216
- }
217
-
218
- const updateOptions = options as UpdateOptions
219
-
220
- const result = await this._collection.updateOne(
221
- { _id: new ObjectId(_id) },
222
- { $set: MongoDBHelper.stringToObjectId(document) },
223
- updateOptions,
224
- )
225
-
226
- return {
227
- modifiedCount: result.modifiedCount,
228
- matchedCount: result.matchedCount,
229
- }
230
- }
231
-
232
- public async updateMany(filter: IDocument[], document: IDocument[], options?: any): Promise<IUpdateManyOutput> {
233
- if (!this._collection) {
234
- throw new Error('Collection not found')
235
- }
236
-
237
- const updateManyOptions = options as UpdateOptions
238
-
239
- const result = await this._collection.updateMany(
240
- filter,
241
- { $set: MongoDBHelper.stringToObjectId(document) },
242
- updateManyOptions,
243
- )
244
-
245
- return {
246
- matchedCount: result.matchedCount,
247
- modifiedCount: result.modifiedCount,
248
- }
249
- }
250
-
251
- public async delete(_id: string, options?: any): Promise<IDeleteOutput> {
252
- if (!this._collection) {
253
- throw new Error('Collection not found')
254
- }
255
-
256
- const deleteOptions = options as DeleteOptions
257
-
258
- const result = await this._collection.deleteOne(
259
- {
260
- _id: new ObjectId(_id),
261
- },
262
- deleteOptions,
263
- )
264
-
265
- return { deletedCount: result.deletedCount }
266
- }
267
-
268
- public async deleteMany(_ids: string[], options?: any): Promise<IDeleteManyOutput> {
269
- if (!this._collection) {
270
- throw new Error('Collection not found')
271
- }
272
-
273
- const deleteOptions = options as DeleteOptions
274
-
275
- const result = await this._collection.deleteMany(
276
- {
277
- _id: {
278
- $in: MongoDBHelper.stringToObjectId(_ids),
279
- },
280
- },
281
- deleteOptions,
282
- )
283
-
284
- return { deletedCount: result.deletedCount }
285
- }
286
-
287
- public async deleteAll(options?: any): Promise<IDeleteManyOutput> {
288
- if (!this._collection) {
289
- throw new Error('Collection not found')
290
- }
291
-
292
- const deleteOptions = options as DeleteOptions
293
-
294
- const result = await this._collection.deleteMany({}, deleteOptions)
295
-
296
- return { deletedCount: result.deletedCount }
297
- }
298
-
299
- public async aggregate(pipeline: IPipeline[], query: IQuery, options?: any): Promise<IAggregateOutput> {
300
- if (!this._collection) {
301
- throw new Error('Collection not found')
302
- }
303
-
304
- const aggregateOptions = options as AggregateOptions
305
-
306
- const cursor = this._collection.aggregate(
307
- [
308
- ...pipeline,
309
- { $skip: (Querystring.page(query.page) - 1) * Querystring.limit(query.pageSize) },
310
- { $limit: Querystring.limit(query.pageSize) },
311
- ],
312
- aggregateOptions,
313
- )
314
-
315
- if (query.sort && Querystring.sort(query.sort)) {
316
- cursor.sort(Querystring.sort(query.sort))
317
- }
318
-
319
- if (Querystring.fields(query.fields, query.excludeFields)) {
320
- cursor.project(Querystring.fields(query.fields, query.excludeFields))
321
- }
322
-
323
- const result = await cursor.toArray()
324
-
325
- const cursorPagination = this._collection.aggregate([...pipeline, { $count: 'totalDocument' }], aggregateOptions)
326
- const resultPagination = await cursorPagination.toArray()
327
-
328
- const totalDocument = resultPagination.length ? resultPagination[0].totalDocument : 0
329
- return {
330
- data: MongoDBHelper.objectIdToString(result) as IRetrieveOutput[],
331
- pagination: {
332
- page: Querystring.page(query.page),
333
- pageCount: Math.ceil(totalDocument / Querystring.limit(query.pageSize)),
334
- pageSize: Querystring.limit(query.pageSize),
335
- totalDocument,
336
- },
337
- }
338
- }
339
- }
@@ -1,63 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
- import { BaseError, find, type IError, type IHttpStatus } from '@point-hub/express-error-handler'
3
- import { MongoServerError } from 'mongodb'
4
-
5
- export function handleSchemaValidation(err: MongoServerError, error: IError) {
6
- // handle schema validation error
7
- error.errors = {} as any
8
- const errorMessage = err.errInfo?.details.schemaRulesNotSatisfied[0].propertiesNotSatisfied
9
- errorMessage.forEach((element: any) => {
10
- const obj: any = {}
11
- obj[element.propertyName] = [element.details[0].reason]
12
- error.errors = obj
13
- })
14
- }
15
-
16
- export function handleUniqueValidation(err: MongoServerError, error: IError) {
17
- // handle unique validation
18
- if (Object.keys(err.keyPattern).length === 1) {
19
- error.errors = {
20
- [Object.keys(err.keyPattern)[0]]: [`The ${Object.keys(err.keyPattern)[0]} is exists.`],
21
- }
22
- } else {
23
- // get keys
24
- const keys = Object.keys(err.keyPattern).reduce((keys: string, key, index) => {
25
- if (index === 0) {
26
- keys += `'`
27
- }
28
- keys += `${key.toString()}`
29
- if (index === Object.keys(err.keyPattern).length - 1) {
30
- keys += `'`
31
- } else {
32
- keys += `, `
33
- }
34
- return keys
35
- }, '')
36
-
37
- // generate error object
38
- const obj = Object.keys(err.keyPattern).reduce((obj: any, key) => {
39
- obj[key] = [`The combination of ${keys.toString()} is exists.`]
40
- return obj
41
- }, {})
42
- error.errors = obj
43
- }
44
- }
45
-
46
- export class MongoErrorHandler extends BaseError {
47
- constructor(err: MongoServerError) {
48
- const error: IError = find(400) as IHttpStatus
49
- if (err.code === 121) {
50
- handleSchemaValidation(err, error)
51
- } else if (err.code === 11000) {
52
- handleUniqueValidation(err, error)
53
- }
54
- super(error)
55
- Object.setPrototypeOf(this, new.target.prototype)
56
- }
57
- get isOperational() {
58
- return true
59
- }
60
- override get name() {
61
- return 'MongoErrorHandler'
62
- }
63
- }