@cyberskill/shared 3.4.0 → 3.6.0

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 (65) hide show
  1. package/dist/config/graphql-codegen/graphql-codegen.type.d.ts +1 -1
  2. package/dist/config/storybook/storybook.preview.js +8 -15
  3. package/dist/config/storybook/storybook.preview.js.map +1 -1
  4. package/dist/config/vitest/vitest.unit.js.map +1 -1
  5. package/dist/constant/index.js +2 -2
  6. package/dist/constant/response-status.d.ts +254 -0
  7. package/dist/constant/response-status.js +65 -1
  8. package/dist/constant/response-status.js.map +1 -1
  9. package/dist/node/cli/index.js +11 -10
  10. package/dist/node/cli/index.js.map +1 -1
  11. package/dist/node/command/command.util.js +32 -20
  12. package/dist/node/command/command.util.js.map +1 -1
  13. package/dist/node/express/express.type.d.ts +2 -0
  14. package/dist/node/express/express.util.js +11 -4
  15. package/dist/node/express/express.util.js.map +1 -1
  16. package/dist/node/log/log.type.d.ts +1 -5
  17. package/dist/node/log/log.type.js.map +1 -1
  18. package/dist/node/log/log.util.d.ts +2 -4
  19. package/dist/node/log/log.util.js +38 -40
  20. package/dist/node/log/log.util.js.map +1 -1
  21. package/dist/node/mongo/mongo.controller.d.ts +3 -1
  22. package/dist/node/mongo/mongo.controller.mongoose.js +75 -78
  23. package/dist/node/mongo/mongo.controller.mongoose.js.map +1 -1
  24. package/dist/node/mongo/mongo.controller.native.d.ts +9 -1
  25. package/dist/node/mongo/mongo.controller.native.js +17 -14
  26. package/dist/node/mongo/mongo.controller.native.js.map +1 -1
  27. package/dist/node/mongo/mongo.controller.type.d.ts +76 -0
  28. package/dist/node/mongo/mongo.dynamic-populate.d.ts +2 -1
  29. package/dist/node/mongo/mongo.dynamic-populate.js +12 -12
  30. package/dist/node/mongo/mongo.dynamic-populate.js.map +1 -1
  31. package/dist/node/mongo/mongo.internal-types.d.ts +81 -0
  32. package/dist/node/mongo/mongo.internal-types.js +40 -0
  33. package/dist/node/mongo/mongo.internal-types.js.map +1 -0
  34. package/dist/node/mongo/mongo.populate.d.ts +2 -1
  35. package/dist/node/mongo/mongo.populate.js +130 -171
  36. package/dist/node/mongo/mongo.populate.js.map +1 -1
  37. package/dist/node/mongo/mongo.type.d.ts +1 -1
  38. package/dist/node/mongo/mongo.type.js.map +1 -1
  39. package/dist/node/mongo/mongo.util.d.ts +7 -7
  40. package/dist/node/mongo/mongo.util.js +34 -32
  41. package/dist/node/mongo/mongo.util.js.map +1 -1
  42. package/dist/node/path/path.constant.d.ts +3 -6
  43. package/dist/node/path/path.constant.js +31 -25
  44. package/dist/node/path/path.constant.js.map +1 -1
  45. package/dist/node/storage/index.js +2 -2
  46. package/dist/node/storage/storage.util.d.ts +6 -0
  47. package/dist/node/storage/storage.util.js +4 -1
  48. package/dist/node/storage/storage.util.js.map +1 -1
  49. package/dist/react/log/log.type.d.ts +1 -5
  50. package/dist/react/log/log.util.d.ts +2 -5
  51. package/dist/react/log/log.util.js +21 -25
  52. package/dist/react/log/log.util.js.map +1 -1
  53. package/dist/util/common/common.util.d.ts +8 -0
  54. package/dist/util/common/common.util.js +4 -1
  55. package/dist/util/common/common.util.js.map +1 -1
  56. package/dist/util/common/index.js +2 -2
  57. package/dist/util/index.d.ts +1 -0
  58. package/dist/util/index.js +7 -6
  59. package/dist/util/log/index.d.ts +2 -0
  60. package/dist/util/log/index.js +2 -0
  61. package/dist/util/log/log.type.d.ts +8 -0
  62. package/dist/util/log/log.util.d.ts +17 -0
  63. package/dist/util/log/log.util.js +14 -0
  64. package/dist/util/log/log.util.js.map +1 -0
  65. package/package.json +83 -40
@@ -1,11 +1,14 @@
1
- import { normalizeMongoFilter as e } from "../../util/object/object.util.js";
2
- import { generateRandomString as t, generateShortId as n, generateSlug as r } from "../../util/string/string.util.js";
3
- import { RESPONSE_STATUS as i } from "../../constant/response-status.js";
4
- import { catchError as a } from "../log/log.util.js";
1
+ import { RESPONSE_STATUS as e } from "../../constant/response-status.js";
2
+ import { normalizeMongoFilter as t } from "../../util/object/object.util.js";
3
+ import { generateRandomString as n, generateShortId as r, generateSlug as i } from "../../util/string/string.util.js";
4
+ import { catchError as a, log as o } from "../log/log.util.js";
5
5
  import "./mongo.constant.js";
6
- import { filterDynamicVirtualsFromPopulate as o, isObject as s, populateDynamicVirtuals as c } from "./mongo.dynamic-populate.js";
6
+ import { filterDynamicVirtualsFromPopulate as s, isObject as c, populateDynamicVirtuals as l } from "./mongo.dynamic-populate.js";
7
7
  //#region src/node/mongo/mongo.controller.mongoose.ts
8
- var l = class {
8
+ function u(e) {
9
+ return e?.toObject?.() ?? e;
10
+ }
11
+ var d = class {
9
12
  defaultLimit;
10
13
  constructor(e, t) {
11
14
  this.model = e, this.defaultLimit = t?.defaultLimit ?? 1e4;
@@ -24,69 +27,67 @@ var l = class {
24
27
  async populateDynamicVirtualsForDocument(e, t) {
25
28
  let n = this.getDynamicVirtuals();
26
29
  if (n && n.length > 0) {
27
- let r = await c(this.model.base, [e], n, t, void 0, this.model);
30
+ let r = await l(this.model.base, [e], n, t, void 0, this.model);
28
31
  return r && r[0] ? r[0] : e;
29
32
  }
30
33
  return e;
31
34
  }
32
35
  async populateDynamicVirtualsForDocuments(e, t) {
33
36
  let n = this.getDynamicVirtuals();
34
- return n && n.length > 0 && e.length > 0 ? await c(this.model.base, e, n, t, void 0, this.model) : e;
37
+ return n && n.length > 0 && e.length > 0 ? await l(this.model.base, e, n, t, void 0, this.model) : e;
35
38
  }
36
- async findOne(t = {}, n = {}, r = {}, s) {
39
+ async findOne(n = {}, r = {}, i = {}, o) {
37
40
  try {
38
- let a = e(t), c = this.model.findOne(a, n, r).maxTimeMS(3e4).lean(), l = o(s, this.getDynamicVirtuals());
41
+ let a = t(n), c = this.model.findOne(a, r, i).maxTimeMS(3e4).lean(), l = s(o, this.getDynamicVirtuals());
39
42
  l && c.populate(l);
40
- let u = await c.exec();
41
- if (!u) return {
43
+ let d = await c.exec();
44
+ return d ? {
45
+ success: !0,
46
+ result: u(await this.populateDynamicVirtualsForDocument(d, o))
47
+ } : {
42
48
  success: !1,
43
49
  message: `No ${this.getModelName()} found.`,
44
- code: i.NOT_FOUND.CODE
45
- };
46
- let d = await this.populateDynamicVirtualsForDocument(u, s);
47
- return {
48
- success: !0,
49
- result: d?.toObject?.() ?? d
50
+ code: e.NOT_FOUND.CODE
50
51
  };
51
52
  } catch (e) {
52
53
  return a(e);
53
54
  }
54
55
  }
55
- async findAll(t = {}, n = {}, r = {}, i) {
56
+ async findAll(e = {}, n = {}, r = {}, i) {
56
57
  try {
57
- let a = e(t), s = this.model.find(a, n, r).maxTimeMS(3e4).lean();
58
- r.limit || s.limit(this.defaultLimit);
59
- let c = o(i, this.getDynamicVirtuals());
60
- c && s.populate(c);
61
- let l = await s.exec();
62
- return {
58
+ let a = t(e), c = this.model.find(a, n, r).maxTimeMS(3e4).lean();
59
+ r.limit || c.limit(this.defaultLimit);
60
+ let l = s(i, this.getDynamicVirtuals());
61
+ l && c.populate(l);
62
+ let d = await c.exec(), f = await this.populateDynamicVirtualsForDocuments(d, i);
63
+ return f.length === this.defaultLimit && !r.limit && o.warn(`[${this.getModelName()}] findAll returned exactly ${this.defaultLimit} documents (the default limit). Results may be truncated. Consider using pagination or setting an explicit limit.`), {
63
64
  success: !0,
64
- result: (await this.populateDynamicVirtualsForDocuments(l, i)).map((e) => e?.toObject?.() ?? e)
65
+ result: f.map((e) => u(e))
65
66
  };
66
67
  } catch (e) {
67
68
  return a(e);
68
69
  }
69
70
  }
70
- async findPaging(t = {}, n = {}) {
71
+ async findPaging(e = {}, n = {}) {
71
72
  try {
72
- let r = e(t), i = this.getDynamicVirtuals(), a = { ...n };
73
- n.populate && (a.populate = o(n.populate, i));
74
- let s = await this.model.paginate(r, a);
73
+ let r = t(e), i = this.getDynamicVirtuals(), a = { ...n };
74
+ n.populate && (a.populate = s(n.populate, i));
75
+ let o = await this.model.paginate(r, a);
75
76
  if (i && i.length > 0) {
76
- let e = await this.populateDynamicVirtualsForDocuments(s.docs, n.populate);
77
+ let e = await this.populateDynamicVirtualsForDocuments(o.docs, n.populate);
77
78
  return {
78
79
  success: !0,
79
80
  result: {
80
- ...s,
81
- docs: e.map((e) => e?.toObject?.() ?? e)
81
+ ...o,
82
+ docs: e.map((e) => u(e))
82
83
  }
83
84
  };
84
85
  }
85
86
  return {
86
87
  success: !0,
87
88
  result: {
88
- ...s,
89
- docs: s.docs.map((e) => e?.toObject?.() ?? e)
89
+ ...o,
90
+ docs: o.docs.map((e) => u(e))
90
91
  }
91
92
  };
92
93
  } catch (e) {
@@ -96,7 +97,7 @@ var l = class {
96
97
  async findPagingAggregate(e, t = {}) {
97
98
  try {
98
99
  let n = this.getDynamicVirtuals(), r = { ...t };
99
- t.populate && (r.populate = o(t.populate, n));
100
+ t.populate && (r.populate = s(t.populate, n));
100
101
  let i = await this.model.aggregatePaginate(this.model.aggregate(e), r), a = await this.populateDynamicVirtualsForDocuments(i.docs, t.populate);
101
102
  return {
102
103
  success: !0,
@@ -109,9 +110,9 @@ var l = class {
109
110
  return a(e);
110
111
  }
111
112
  }
112
- async count(t = {}) {
113
+ async count(e = {}) {
113
114
  try {
114
- let n = e(t);
115
+ let n = t(e);
115
116
  return {
116
117
  success: !0,
117
118
  result: await this.model.countDocuments(n)
@@ -141,11 +142,11 @@ var l = class {
141
142
  return a(e);
142
143
  }
143
144
  }
144
- async updateOne(t = {}, n = {}, r = {}) {
145
+ async updateOne(n = {}, r = {}, i = {}) {
145
146
  try {
146
- let a = e(t), o = await this.model.findOneAndUpdate(a, n, {
147
+ let a = t(n), o = await this.model.findOneAndUpdate(a, r, {
147
148
  new: !0,
148
- ...r
149
+ ...i
149
150
  }).exec();
150
151
  return o ? {
151
152
  success: !0,
@@ -153,15 +154,15 @@ var l = class {
153
154
  } : {
154
155
  success: !1,
155
156
  message: `Failed to update ${this.getModelName()}.`,
156
- code: i.NOT_FOUND.CODE
157
+ code: e.NOT_FOUND.CODE
157
158
  };
158
159
  } catch (e) {
159
160
  return a(e);
160
161
  }
161
162
  }
162
- async updateMany(t = {}, n = {}, r = {}) {
163
+ async updateMany(e = {}, n = {}, r = {}) {
163
164
  try {
164
- let i = e(t);
165
+ let i = t(e);
165
166
  return {
166
167
  success: !0,
167
168
  result: await this.model.updateMany(i, n, r).exec()
@@ -170,28 +171,28 @@ var l = class {
170
171
  return a(e);
171
172
  }
172
173
  }
173
- async deleteOne(t = {}, n = {}) {
174
+ async deleteOne(n = {}, r = {}) {
174
175
  try {
175
- let r = e(t), a = await this.model.findOneAndDelete(r, n).exec();
176
+ let i = t(n), a = await this.model.findOneAndDelete(i, r).exec();
176
177
  return a ? {
177
178
  success: !0,
178
179
  result: a?.toObject?.() ?? a
179
180
  } : {
180
181
  success: !1,
181
182
  message: `No ${this.getModelName()} found to delete.`,
182
- code: i.NOT_FOUND.CODE
183
+ code: e.NOT_FOUND.CODE
183
184
  };
184
185
  } catch (e) {
185
186
  return a(e);
186
187
  }
187
188
  }
188
- async deleteMany(t = {}, n = {}) {
189
+ async deleteMany(n = {}, r = {}) {
189
190
  try {
190
- let r = e(t), a = await this.model.deleteMany(r, n).exec();
191
+ let i = t(n), a = await this.model.deleteMany(i, r).exec();
191
192
  return a.deletedCount === 0 ? {
192
193
  success: !1,
193
194
  message: "No documents found to delete.",
194
- code: i.NOT_FOUND.CODE
195
+ code: e.NOT_FOUND.CODE
195
196
  } : {
196
197
  success: !0,
197
198
  result: a
@@ -200,20 +201,16 @@ var l = class {
200
201
  return a(e);
201
202
  }
202
203
  }
203
- async createShortId(e, t = 4) {
204
+ async createShortId(t, n = 4) {
204
205
  try {
205
- let r = Array.from({ length: 10 }, (r, i) => n(e, i + t)), a = (await Promise.all(r.map((e) => this.model.exists({ shortId: e })))).findIndex((e) => !e);
206
- if (a !== -1) {
207
- let e = r[a];
208
- if (e) return {
209
- success: !0,
210
- result: e
211
- };
212
- }
213
- return {
206
+ let i = Array.from({ length: 10 }, (e, i) => r(t, i + n)), a = await this.model.find({ shortId: { $in: i } }).select("shortId").lean(), o = new Set(a.map((e) => e.shortId)), s = i.find((e) => !o.has(e));
207
+ return s ? {
208
+ success: !0,
209
+ result: s
210
+ } : {
214
211
  success: !1,
215
212
  message: "Failed to create a unique shortId",
216
- code: i.INTERNAL_SERVER_ERROR.CODE
213
+ code: e.INTERNAL_SERVER_ERROR.CODE
217
214
  };
218
215
  } catch (e) {
219
216
  return a(e);
@@ -229,29 +226,29 @@ var l = class {
229
226
  $or: [{ slug: e }, ...r ? [{ slugHistory: e }] : []]
230
227
  };
231
228
  }
232
- async createUniqueSlug({ slug: e, field: n, isObject: i, haveHistory: a, filter: o }) {
229
+ async createUniqueSlug({ slug: e, field: t, isObject: r, haveHistory: a, filter: o }) {
233
230
  if (!e || typeof e != "string") throw Error("Invalid slug provided: must be a non-empty string");
234
- let s = r(e);
231
+ let s = i(e);
235
232
  if (!await this.model.exists(this.createSlugQuery({
236
233
  slug: s,
237
- field: n,
238
- isObject: i,
234
+ field: t,
235
+ isObject: r,
239
236
  haveHistory: a,
240
237
  filter: o
241
238
  }))) return s;
242
239
  let c = Array.from({ length: 100 }, (e, t) => `${s}-${t + 1}`), l = c.map((e) => this.createSlugQuery({
243
240
  slug: e,
244
- field: n,
245
- isObject: i,
241
+ field: t,
242
+ isObject: r,
246
243
  haveHistory: a,
247
244
  filter: o
248
- })), u = i ? `slug.${n}` : "slug", d = await this.model.find({ $or: l.map((e) => e.$or).flat() }).select(u).lean(), f = new Set(d.map((e) => i ? e?.slug?.[n] : e?.slug));
249
- return c.find((e) => !f.has(e)) || `${s}-${Date.now()}-${t(6)}`;
245
+ })), u = r ? `slug.${t}` : "slug", d = await this.model.find({ $or: l.map((e) => e.$or).flat() }).select(u).lean(), f = new Set(d.map((e) => r ? e.slug?.[t] : e.slug));
246
+ return c.find((e) => !f.has(e)) || `${s}-${Date.now()}-${n(6)}`;
250
247
  }
251
248
  async createSlug({ field: e, from: t, filter: n, haveHistory: r }) {
252
249
  try {
253
250
  let i = t[e];
254
- return s(i) ? {
251
+ return c(i) ? {
255
252
  success: !0,
256
253
  result: Object.fromEntries(await Promise.all(Object.entries(i).map(async ([e, t]) => [e, await this.createUniqueSlug({
257
254
  slug: t,
@@ -274,17 +271,17 @@ var l = class {
274
271
  return a(e);
275
272
  }
276
273
  }
277
- async checkSlug({ slug: e, field: t, from: n, filter: i, haveHistory: o }) {
274
+ async checkSlug({ slug: e, field: t, from: n, filter: r, haveHistory: o }) {
278
275
  try {
279
276
  let a = n[t];
280
- if (s(a)) {
281
- let e = Object.values(a).map((e) => r(e));
277
+ if (c(a)) {
278
+ let e = Object.values(a).map((e) => i(e));
282
279
  return (await Promise.all(e.map((e) => this.model.exists(this.createSlugQuery({
283
280
  slug: e,
284
281
  field: t,
285
282
  isObject: !0,
286
283
  haveHistory: o,
287
- filter: i
284
+ filter: r
288
285
  }))))).some((e) => e) ? {
289
286
  success: !0,
290
287
  result: !0
@@ -293,14 +290,14 @@ var l = class {
293
290
  result: !1
294
291
  };
295
292
  }
296
- let c = r(e);
293
+ let s = i(e);
297
294
  return {
298
295
  success: !0,
299
296
  result: await this.model.exists(this.createSlugQuery({
300
- slug: c,
297
+ slug: s,
301
298
  field: t,
302
299
  isObject: !1,
303
- filter: i
300
+ filter: r
304
301
  })) !== null
305
302
  };
306
303
  } catch (e) {
@@ -329,6 +326,6 @@ var l = class {
329
326
  }
330
327
  };
331
328
  //#endregion
332
- export { l as MongooseController };
329
+ export { d as MongooseController };
333
330
 
334
331
  //# sourceMappingURL=mongo.controller.mongoose.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mongo.controller.mongoose.js","names":[],"sources":["../../../src/node/mongo/mongo.controller.mongoose.ts"],"sourcesContent":["import type { I_Return } from '#typescript/index.js';\n\nimport { RESPONSE_STATUS } from '#constant/index.js';\nimport { normalizeMongoFilter } from '#util/index.js';\nimport { generateRandomString, generateShortId, generateSlug } from '#util/string/index.js';\n\nimport type { C_Document, I_DeleteOptionsExtended, I_DynamicVirtualConfig, I_ExtendedModel, I_Input_CheckSlug, I_Input_CreateSlug, I_Input_GenerateSlug, I_PaginateOptionsWithPopulate, I_UpdateOptionsExtended, T_AggregatePaginateResult, T_DeleteResult, T_Input_Populate, T_InsertManyOptions, T_PaginateResult, T_PipelineStage, T_PopulateOptions, T_ProjectionType, T_QueryFilter, T_QueryOptions, T_UpdateQuery, T_UpdateResult } from './mongo.type.js';\n\nimport { catchError } from '../log/index.js';\nimport { MONGO_SLUG_MAX_ATTEMPTS } from './mongo.constant.js';\nimport { filterDynamicVirtualsFromPopulate, isObject, populateDynamicVirtuals } from './mongo.dynamic-populate.js';\n\n/** Internal shape of a single virtual config stored on the model. */\ninterface I_VirtualConfig {\n name: string;\n options?: { ref?: unknown };\n}\n\n/**\n * Mongoose controller for database operations with advanced features.\n * This class provides a comprehensive interface for Mongoose operations including\n * pagination, aggregation, slug generation, and short ID creation.\n */\nexport class MongooseController<T extends Partial<C_Document>> {\n private defaultLimit: number;\n\n /**\n * Creates a new Mongoose controller instance.\n *\n * @param model - The Mongoose model to operate on.\n * @param options - Optional configuration for the controller.\n * @param options.defaultLimit - Maximum documents returned by findAll when no limit is specified (default: 10,000).\n */\n constructor(private model: I_ExtendedModel<T>, options?: { defaultLimit?: number }) {\n this.defaultLimit = options?.defaultLimit ?? 10_000;\n }\n\n /**\n * Gets the model name for logging and error messages.\n *\n * @returns The name of the model.\n */\n private getModelName(): string {\n return this.model.modelName;\n }\n\n /**\n * Gets the dynamic virtuals configuration from the model instance.\n *\n * @returns Array of dynamic virtual configurations or undefined if none exist.\n */\n private getDynamicVirtuals(): I_DynamicVirtualConfig<T>[] | undefined {\n const model = this.model as I_ExtendedModel<T> & { _virtualConfigs?: I_VirtualConfig[] };\n\n if (model._virtualConfigs) {\n const dynamicOnly = model._virtualConfigs.filter(\n v => typeof v.options?.ref === 'function',\n ) as unknown as I_DynamicVirtualConfig<T>[];\n\n if (dynamicOnly.length > 0) {\n return dynamicOnly;\n }\n }\n\n const schemaStatics = this.model.schema.statics as { [key: string]: unknown };\n\n return schemaStatics['_dynamicVirtuals'] as I_DynamicVirtualConfig<T>[] | undefined;\n }\n\n /**\n * Populates dynamic virtuals for a single document.\n *\n * @param result - The document to populate dynamic virtuals for.\n * @param populate - The populate options to determine which virtuals to populate.\n * @returns The document with dynamic virtuals populated.\n */\n private async populateDynamicVirtualsForDocument(result: T, populate?: T_Input_Populate): Promise<T> {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0) {\n const populatedArr = await populateDynamicVirtuals(this.model.base, [result], dynamicVirtuals, populate, undefined, this.model);\n\n return (populatedArr && populatedArr[0]) ? populatedArr[0] as T : result;\n }\n\n return result;\n }\n\n /**\n * Populates dynamic virtuals for an array of documents.\n *\n * @param results - The documents to populate dynamic virtuals for.\n * @param populate - The populate options to determine which virtuals to populate.\n * @returns The documents with dynamic virtuals populated.\n */\n private async populateDynamicVirtualsForDocuments(results: T[], populate?: T_Input_Populate): Promise<T[]> {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0 && results.length > 0) {\n const populatedResults = await populateDynamicVirtuals(this.model.base, results, dynamicVirtuals, populate, undefined, this.model) as T[];\n\n return populatedResults;\n }\n\n return results;\n }\n\n /**\n * Finds a single document with optional population and projection.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find the document.\n * @param projection - The fields to include/exclude in the result.\n * @param options - Query options for the operation.\n * @param populate - Population configuration for related documents.\n * @returns A promise that resolves to a standardized response with the found document.\n */\n async findOne(\n filter: T_QueryFilter<T> = {},\n projection: T_ProjectionType<T> = {},\n options: T_QueryOptions<T> = {},\n populate?: T_Input_Populate,\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const query = this.model.findOne(normalizedFilter, projection, options).maxTimeMS(30_000).lean();\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const regularPopulate = filterDynamicVirtualsFromPopulate(populate, dynamicVirtuals);\n\n if (regularPopulate) {\n query.populate(regularPopulate as T_PopulateOptions);\n }\n\n const result = await query.exec();\n\n if (!result) {\n return {\n success: false,\n message: `No ${this.getModelName()} found.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n const finalResult = await this.populateDynamicVirtualsForDocument(result, populate);\n\n return { success: true, result: finalResult?.toObject?.() ?? finalResult };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Finds all documents with optional population and projection.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find documents.\n * @param projection - The fields to include/exclude in the result.\n * @param options - Query options for the operation.\n * @param populate - Population configuration for related documents.\n * @returns A promise that resolves to a standardized response with the found documents.\n */\n async findAll(\n filter: T_QueryFilter<T> = {},\n projection: T_ProjectionType<T> = {},\n options: T_QueryOptions<T> = {},\n populate?: T_Input_Populate,\n ): Promise<I_Return<T[]>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const query = this.model.find(normalizedFilter, projection, options).maxTimeMS(30_000).lean();\n\n if (!options.limit) {\n query.limit(this.defaultLimit);\n }\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const regularPopulate = filterDynamicVirtualsFromPopulate(populate, dynamicVirtuals);\n\n if (regularPopulate) {\n query.populate(regularPopulate as T_PopulateOptions);\n }\n\n const result = await query.exec();\n\n const finalResult = await this.populateDynamicVirtualsForDocuments(result, populate);\n\n return { success: true, result: finalResult.map(item => item?.toObject?.() ?? item) };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Finds documents with pagination support.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find documents.\n * @param options - Pagination options including page, limit, and population.\n * @returns A promise that resolves to a standardized response with paginated results.\n */\n async findPaging(\n filter: T_QueryFilter<T> = {},\n options: I_PaginateOptionsWithPopulate = {},\n ): Promise<I_Return<T_PaginateResult<T>>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const filteredOptions = { ...options };\n\n if (options.populate) {\n filteredOptions.populate = filterDynamicVirtualsFromPopulate(options.populate, dynamicVirtuals);\n }\n\n const result = await this.model.paginate(normalizedFilter, filteredOptions);\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0) {\n const populatedDocs = await this.populateDynamicVirtualsForDocuments(result.docs, options.populate);\n\n return { success: true, result: { ...result, docs: populatedDocs.map(item => item?.toObject?.() ?? item) } };\n }\n\n return { success: true, result: { ...result, docs: result.docs.map(item => item?.toObject?.() ?? item) } };\n }\n catch (error) {\n return catchError<T_PaginateResult<T>>(error);\n }\n }\n\n /**\n * Performs aggregation with pagination support.\n *\n * @param pipeline - The aggregation pipeline stages.\n * @param options - Pagination options for the aggregation result.\n * @returns A promise that resolves to a standardized response with paginated aggregation results.\n */\n async findPagingAggregate(\n pipeline: T_PipelineStage[],\n options: I_PaginateOptionsWithPopulate = {},\n ): Promise<I_Return<T_AggregatePaginateResult<T>>> {\n try {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const filteredOptions = { ...options };\n\n if (options.populate) {\n filteredOptions.populate = filterDynamicVirtualsFromPopulate(options.populate, dynamicVirtuals);\n }\n\n const result = await this.model.aggregatePaginate(\n this.model.aggregate(pipeline),\n filteredOptions,\n );\n\n const finalDocs = await this.populateDynamicVirtualsForDocuments(result.docs, options.populate);\n\n return { success: true, result: { ...result, docs: finalDocs.map(item => item?.toObject?.() ?? item) } };\n }\n catch (error) {\n return catchError<T_AggregatePaginateResult<T>>(error);\n }\n }\n\n /**\n * Counts documents matching the filter criteria.\n *\n * @param filter - The filter criteria to count documents.\n * @returns A promise that resolves to a standardized response with the document count.\n */\n async count(filter: T_QueryFilter<T> = {}): Promise<I_Return<number>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model.countDocuments(normalizedFilter);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<number>(error);\n }\n }\n\n /**\n * Creates a single document.\n *\n * @param doc - The document to create.\n * @returns A promise that resolves to a standardized response with the created document.\n */\n async createOne(doc: T | Partial<T>): Promise<I_Return<T>> {\n try {\n const result = await this.model.create(doc as unknown as Parameters<typeof this.model.create>[0]);\n\n return { success: true, result: (result as T)?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Creates multiple documents with bulk insertion.\n *\n * @param docs - An array of documents to create.\n * @param options - Options for the bulk insertion operation.\n * @returns A promise that resolves to a standardized response with the created documents.\n */\n async createMany(\n docs: (T | Partial<T>)[],\n options: T_InsertManyOptions = {},\n ): Promise<I_Return<T[]>> {\n try {\n const createdDocuments = await this.model.insertMany(docs, options);\n\n return { success: true, result: createdDocuments.map(item => item?.toObject?.() ?? item) as T[] };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Updates a single document and returns the updated version.\n *\n * @param filter - The filter criteria to find the document to update.\n * @param update - The update data to apply.\n * @param options - Options for the update operation.\n * @returns A promise that resolves to a standardized response with the updated document.\n */\n async updateOne(\n filter: T_QueryFilter<T> = {},\n update: T_UpdateQuery<T> = {},\n options: I_UpdateOptionsExtended = {},\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .findOneAndUpdate(normalizedFilter, update, {\n new: true,\n ...options,\n })\n .exec();\n\n if (!result) {\n return {\n success: false,\n message: `Failed to update ${this.getModelName()}.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result: result?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Updates multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to update.\n * @param update - The update data to apply.\n * @param options - Options for the update operation.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateMany(\n filter: T_QueryFilter<T> = {},\n update: T_UpdateQuery<T> = {},\n options: I_UpdateOptionsExtended = {},\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .updateMany(normalizedFilter, update, options)\n .exec();\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Deletes a single document and returns the deleted version.\n *\n * @param filter - The filter criteria to find the document to delete.\n * @param options - Options for the delete operation.\n * @returns A promise that resolves to a standardized response with the deleted document.\n */\n async deleteOne(\n filter: T_QueryFilter<T> = {},\n options: I_DeleteOptionsExtended = {},\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .findOneAndDelete(normalizedFilter, options)\n .exec();\n\n if (!result) {\n return {\n success: false,\n message: `No ${this.getModelName()} found to delete.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result: result?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Deletes multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to delete.\n * @param options - Options for the delete operation.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteMany(\n filter: T_QueryFilter<T> = {},\n options: I_DeleteOptionsExtended = {},\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model.deleteMany(normalizedFilter, options).exec();\n\n if (result.deletedCount === 0) {\n return {\n success: false,\n message: `No documents found to delete.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n\n /**\n * Creates a unique short ID based on a given ID.\n * This method generates multiple short IDs with increasing lengths and finds the first available one.\n *\n * @param id - The base ID to generate short IDs from.\n * @param length - The initial length for short ID generation (default: 4).\n * @returns A promise that resolves to a standardized response with the unique short ID.\n */\n async createShortId(id: string, length = 4): Promise<I_Return<string>> {\n try {\n const maxRetries = 10;\n const shortIds = Array.from({ length: maxRetries }, (_, index) =>\n generateShortId(id, index + length));\n\n const existenceChecks = await Promise.all(\n shortIds.map(shortId => this.model.exists({ shortId })),\n );\n\n const availableIndex = existenceChecks.findIndex(exists => !exists);\n\n if (availableIndex !== -1) {\n const availableShortId = shortIds[availableIndex];\n\n if (availableShortId) {\n return { success: true, result: availableShortId };\n }\n }\n\n return {\n success: false,\n message: 'Failed to create a unique shortId',\n code: RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE,\n };\n }\n catch (error) {\n return catchError<string>(error);\n }\n }\n\n /**\n * Creates a query for slug existence checking.\n * This method generates a query that checks for slug existence in both current and historical slug fields.\n *\n * @param options - Configuration for slug query generation including slug, field, and filter.\n * @param options.slug - The slug string to check for existence.\n * @param options.field - The field name for object-based slug checking.\n * @param options.isObject - Whether the slug is stored as an object with nested fields.\n * @param options.haveHistory - Whether to check historical slug fields for existence.\n * @param options.filter - Additional filter conditions to apply to the query.\n * @returns A MongoDB query object for checking slug existence.\n */\n createSlugQuery({ slug, field, isObject, haveHistory = false, filter }: I_Input_GenerateSlug<T>) {\n const baseFilter = { ...(filter ?? {}) };\n\n return isObject\n ? {\n ...baseFilter,\n $or: [\n { [`slug.${field}`]: slug },\n ...(haveHistory ? [{ slugHistory: { $elemMatch: { [`slug.${field}`]: slug } } }] : []),\n ],\n }\n : {\n ...baseFilter,\n $or: [\n { slug },\n ...(haveHistory ? [{ slugHistory: slug }] : []),\n ],\n };\n }\n\n /**\n * Creates a unique slug based on a given string.\n * This method generates multiple slug variations and finds the first available one.\n *\n * @param options - Configuration for slug generation including slug, field, and filter.\n * @param options.slug - The base slug string to make unique.\n * @param options.field - The field name for object-based slug checking.\n * @param options.isObject - Whether the slug is stored as an object with nested fields.\n * @param options.haveHistory - Whether to check historical slug fields for uniqueness.\n * @param options.filter - Additional filter conditions to apply when checking slug existence.\n * @returns A promise that resolves to a unique slug string.\n */\n async createUniqueSlug({ slug, field, isObject, haveHistory, filter }: I_Input_GenerateSlug<T>): Promise<string> {\n if (!slug || typeof slug !== 'string') {\n throw new Error('Invalid slug provided: must be a non-empty string');\n }\n\n const baseSlug = generateSlug(slug);\n\n const baseExists = await this.model.exists(\n this.createSlugQuery({ slug: baseSlug, field, isObject, haveHistory, filter }),\n );\n\n if (!baseExists) {\n return baseSlug;\n }\n\n // Batch query: check all slug variations in a single database call instead of N+1 sequential queries\n const variants = Array.from(\n { length: MONGO_SLUG_MAX_ATTEMPTS },\n (_, i) => `${baseSlug}-${i + 1}`,\n );\n\n const slugQueries = variants.map(s =>\n this.createSlugQuery({ slug: s, field, isObject, haveHistory, filter }),\n );\n\n const slugField = isObject ? `slug.${field as string}` : 'slug';\n const existingDocs = await this.model\n .find({ $or: slugQueries.map(q => q.$or).flat() })\n .select(slugField)\n .lean();\n\n const existingSlugs = new Set(\n existingDocs.map((d: any) => isObject ? d?.slug?.[field as string] : d?.slug),\n );\n\n const available = variants.find(s => !existingSlugs.has(s));\n\n if (available) {\n return available;\n }\n\n const timestamp = Date.now();\n const randomSuffix = generateRandomString(6);\n\n return `${baseSlug}-${timestamp}-${randomSuffix}`;\n }\n\n /**\n * Creates a slug for a document field.\n * This method handles both simple string fields and object fields with nested slug generation.\n *\n * @param options - Configuration for slug creation including field, source document, and filter.\n * @param options.field - The field name to create a slug for.\n * @param options.from - The source document containing the field value.\n * @param options.haveHistory - Whether to check historical slug fields for uniqueness.\n * @param options.filter - Additional filter conditions to apply when checking slug existence.\n * @returns A promise that resolves to a standardized response with the created slug(s).\n */\n async createSlug<R = string>({ field, from, filter, haveHistory }: I_Input_CreateSlug<T>): Promise<I_Return<R>> {\n try {\n const fieldValue = from[field as keyof T];\n const isObjectValue = isObject(fieldValue);\n\n if (isObjectValue) {\n const uniqueSlug = Object.fromEntries(\n await Promise.all(\n Object.entries(fieldValue).map(async ([key, value]) => {\n const uniqueSlugForKey = await this.createUniqueSlug({\n slug: value as string,\n field: key,\n isObject: true,\n haveHistory,\n filter,\n });\n return [key, uniqueSlugForKey];\n }),\n ),\n );\n\n return { success: true, result: uniqueSlug as R };\n }\n\n const uniqueSlug = await this.createUniqueSlug({\n slug: fieldValue as string,\n field,\n isObject: false,\n haveHistory,\n filter,\n });\n\n return { success: true, result: uniqueSlug as R };\n }\n catch (error) {\n return catchError<R>(error);\n }\n }\n\n /**\n * Checks if a slug already exists in the collection.\n * This method verifies slug existence in both current and historical slug fields.\n *\n * @param options - Configuration for slug checking including slug, field, source document, and filter.\n * @param options.slug - The slug string to check for existence.\n * @param options.field - The field name for object-based slug checking.\n * @param options.from - The source document containing the field value.\n * @param options.haveHistory - Whether to check historical slug fields for existence.\n * @param options.filter - Additional filter conditions to apply to the query.\n * @returns A promise that resolves to a standardized response indicating whether the slug exists.\n */\n async checkSlug({ slug, field, from, filter, haveHistory }: I_Input_CheckSlug<T>): Promise<I_Return<boolean>> {\n try {\n const fieldValue = from[field as keyof T];\n const isObjectValue = isObject(fieldValue);\n\n if (isObjectValue) {\n const values = Object.values(fieldValue);\n const nestedSlugs = values.map(value => generateSlug(value as string));\n\n const existenceChecks = await Promise.all(\n nestedSlugs.map(nestedSlug =>\n this.model.exists(this.createSlugQuery({\n slug: nestedSlug,\n field,\n isObject: true,\n haveHistory,\n filter,\n })),\n ),\n );\n\n if (existenceChecks.some(exists => exists)) {\n return { success: true, result: true };\n }\n\n return { success: true, result: false };\n }\n\n const baseSlug = generateSlug(slug);\n const exists = await this.model.exists(this.createSlugQuery({\n slug: baseSlug,\n field,\n isObject: false,\n filter,\n }));\n\n return { success: true, result: exists !== null };\n }\n catch (error) {\n return catchError<boolean>(error);\n }\n }\n\n /**\n * Performs aggregation operations on the collection.\n *\n * @param pipeline - The aggregation pipeline stages to execute.\n * @returns A promise that resolves to a standardized response with the aggregation results.\n */\n async aggregate(pipeline: T_PipelineStage[]): Promise<I_Return<T[]>> {\n try {\n const result = await this.model.aggregate<T>(pipeline);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Retrieves distinct values for the specified key from the collection.\n *\n * @param key - The field for which to return distinct values.\n * @param filter - The filter query to apply (optional).\n * @param options - Additional options for the distinct operation (optional).\n * @returns A promise that resolves to a standardized response with the array of distinct values.\n */\n async distinct(\n key: string,\n filter: T_QueryFilter<T> = {},\n options: T_QueryOptions<T> = {},\n ): Promise<I_Return<unknown[]>> {\n try {\n const result = await this.model.distinct(key, filter, options);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<unknown[]>(error);\n }\n }\n}\n"],"mappings":";;;;;;;AAuBA,IAAa,IAAb,MAA+D;CAC3D;CASA,YAAY,GAAmC,GAAqC;AAChF,EADgB,KAAA,QAAA,GAChB,KAAK,eAAe,GAAS,gBAAgB;;CAQjD,eAA+B;AAC3B,SAAO,KAAK,MAAM;;CAQtB,qBAAsE;EAClE,IAAM,IAAQ,KAAK;AAEnB,MAAI,EAAM,iBAAiB;GACvB,IAAM,IAAc,EAAM,gBAAgB,QACtC,MAAK,OAAO,EAAE,SAAS,OAAQ,WAClC;AAED,OAAI,EAAY,SAAS,EACrB,QAAO;;AAMf,SAFsB,KAAK,MAAM,OAAO,QAEnB;;CAUzB,MAAc,mCAAmC,GAAW,GAAyC;EACjG,IAAM,IAAkB,KAAK,oBAAoB;AAEjD,MAAI,KAAmB,EAAgB,SAAS,GAAG;GAC/C,IAAM,IAAe,MAAM,EAAwB,KAAK,MAAM,MAAM,CAAC,EAAO,EAAE,GAAiB,GAAU,KAAA,GAAW,KAAK,MAAM;AAE/H,UAAQ,KAAgB,EAAa,KAAM,EAAa,KAAU;;AAGtE,SAAO;;CAUX,MAAc,oCAAoC,GAAc,GAA2C;EACvG,IAAM,IAAkB,KAAK,oBAAoB;AAQjD,SANI,KAAmB,EAAgB,SAAS,KAAK,EAAQ,SAAS,IACzC,MAAM,EAAwB,KAAK,MAAM,MAAM,GAAS,GAAiB,GAAU,KAAA,GAAW,KAAK,MAAM,GAK/H;;CAaX,MAAM,QACF,IAA2B,EAAE,EAC7B,IAAkC,EAAE,EACpC,IAA6B,EAAE,EAC/B,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K,MAAM,SAAS,GAAK,GAAQ,EAAQ;IAE9B;WAE7B,GAAO;AACV,UAAO,EAAsB,EAAM"}
1
+ {"version":3,"file":"mongo.controller.mongoose.js","names":[],"sources":["../../../src/node/mongo/mongo.controller.mongoose.ts"],"sourcesContent":["import type { I_Return } from '#typescript/index.js';\n\nimport { RESPONSE_STATUS } from '#constant/index.js';\nimport { normalizeMongoFilter } from '#util/index.js';\nimport { generateRandomString, generateShortId, generateSlug } from '#util/string/index.js';\n\nimport type { C_Document, I_DeleteOptionsExtended, I_DynamicVirtualConfig, I_ExtendedModel, I_Input_CheckSlug, I_Input_CreateSlug, I_Input_GenerateSlug, I_PaginateOptionsWithPopulate, I_UpdateOptionsExtended, T_AggregatePaginateResult, T_DeleteResult, T_Input_Populate, T_InsertManyOptions, T_PaginateResult, T_PipelineStage, T_PopulateOptions, T_ProjectionType, T_QueryFilter, T_QueryOptions, T_UpdateQuery, T_UpdateResult } from './mongo.type.js';\n\nimport { catchError, log } from '../log/index.js';\nimport { MONGO_SLUG_MAX_ATTEMPTS } from './mongo.constant.js';\nimport { filterDynamicVirtualsFromPopulate, isObject, populateDynamicVirtuals } from './mongo.dynamic-populate.js';\n\n/**\n * Converts a Mongoose document to a plain object, handling the case where\n * the document may already be a plain object (e.g., from `.lean()`).\n *\n * @param doc - The document or plain object.\n * @returns The plain object representation.\n */\nfunction toPlainObject<T>(doc: T): T {\n return (doc as T & { toObject?: () => T })?.toObject?.() ?? doc;\n}\n\n/** Internal shape of a single virtual config stored on the model. */\ninterface I_VirtualConfig {\n name: string;\n options?: { ref?: unknown };\n}\n\n/**\n * Mongoose controller for database operations with advanced features.\n * This class provides a comprehensive interface for Mongoose operations including\n * pagination, aggregation, slug generation, and short ID creation.\n */\nexport class MongooseController<T extends Partial<C_Document>> {\n private defaultLimit: number;\n\n /**\n * Creates a new Mongoose controller instance.\n *\n * @param model - The Mongoose model to operate on.\n * @param options - Optional configuration for the controller.\n * @param options.defaultLimit - Maximum documents returned by findAll when no limit is specified (default: 10,000).\n */\n constructor(private model: I_ExtendedModel<T>, options?: { defaultLimit?: number }) {\n this.defaultLimit = options?.defaultLimit ?? 10_000;\n }\n\n /**\n * Gets the model name for logging and error messages.\n *\n * @returns The name of the model.\n */\n private getModelName(): string {\n return this.model.modelName;\n }\n\n /**\n * Gets the dynamic virtuals configuration from the model instance.\n *\n * @returns Array of dynamic virtual configurations or undefined if none exist.\n */\n private getDynamicVirtuals(): I_DynamicVirtualConfig<T>[] | undefined {\n const model = this.model as I_ExtendedModel<T> & { _virtualConfigs?: I_VirtualConfig[] };\n\n if (model._virtualConfigs) {\n const dynamicOnly = model._virtualConfigs.filter(\n v => typeof v.options?.ref === 'function',\n ) as unknown as I_DynamicVirtualConfig<T>[];\n\n if (dynamicOnly.length > 0) {\n return dynamicOnly;\n }\n }\n\n const schemaStatics = this.model.schema.statics as { [key: string]: unknown };\n\n return schemaStatics['_dynamicVirtuals'] as I_DynamicVirtualConfig<T>[] | undefined;\n }\n\n /**\n * Populates dynamic virtuals for a single document.\n *\n * @param result - The document to populate dynamic virtuals for.\n * @param populate - The populate options to determine which virtuals to populate.\n * @returns The document with dynamic virtuals populated.\n */\n private async populateDynamicVirtualsForDocument(result: T, populate?: T_Input_Populate): Promise<T> {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0) {\n const populatedArr = await populateDynamicVirtuals(this.model.base, [result], dynamicVirtuals, populate, undefined, this.model);\n\n return (populatedArr && populatedArr[0]) ? populatedArr[0] as T : result;\n }\n\n return result;\n }\n\n /**\n * Populates dynamic virtuals for an array of documents.\n *\n * @param results - The documents to populate dynamic virtuals for.\n * @param populate - The populate options to determine which virtuals to populate.\n * @returns The documents with dynamic virtuals populated.\n */\n private async populateDynamicVirtualsForDocuments(results: T[], populate?: T_Input_Populate): Promise<T[]> {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0 && results.length > 0) {\n const populatedResults = await populateDynamicVirtuals(this.model.base, results, dynamicVirtuals, populate, undefined, this.model) as T[];\n\n return populatedResults;\n }\n\n return results;\n }\n\n /**\n * Finds a single document with optional population and projection.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find the document.\n * @param projection - The fields to include/exclude in the result.\n * @param options - Query options for the operation.\n * @param populate - Population configuration for related documents.\n * @returns A promise that resolves to a standardized response with the found document.\n */\n async findOne(\n filter: T_QueryFilter<T> = {},\n projection: T_ProjectionType<T> = {},\n options: T_QueryOptions<T> = {},\n populate?: T_Input_Populate,\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const query = this.model.findOne(normalizedFilter, projection, options).maxTimeMS(30_000).lean();\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const regularPopulate = filterDynamicVirtualsFromPopulate(populate, dynamicVirtuals);\n\n if (regularPopulate) {\n query.populate(regularPopulate as T_PopulateOptions);\n }\n\n const result = await query.exec();\n\n if (!result) {\n return {\n success: false,\n message: `No ${this.getModelName()} found.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n const finalResult = await this.populateDynamicVirtualsForDocument(result, populate);\n\n return { success: true, result: toPlainObject(finalResult) };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Finds all documents with optional population and projection.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find documents.\n * @param projection - The fields to include/exclude in the result.\n * @param options - Query options for the operation.\n * @param populate - Population configuration for related documents.\n * @returns A promise that resolves to a standardized response with the found documents.\n */\n async findAll(\n filter: T_QueryFilter<T> = {},\n projection: T_ProjectionType<T> = {},\n options: T_QueryOptions<T> = {},\n populate?: T_Input_Populate,\n ): Promise<I_Return<T[]>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const query = this.model.find(normalizedFilter, projection, options).maxTimeMS(30_000).lean();\n\n if (!options.limit) {\n query.limit(this.defaultLimit);\n }\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const regularPopulate = filterDynamicVirtualsFromPopulate(populate, dynamicVirtuals);\n\n if (regularPopulate) {\n query.populate(regularPopulate as T_PopulateOptions);\n }\n\n const result = await query.exec();\n\n const finalResult = await this.populateDynamicVirtualsForDocuments(result, populate);\n\n if (finalResult.length === this.defaultLimit && !options.limit) {\n log.warn(`[${this.getModelName()}] findAll returned exactly ${this.defaultLimit} documents (the default limit). Results may be truncated. Consider using pagination or setting an explicit limit.`);\n }\n\n return { success: true, result: finalResult.map(item => toPlainObject(item)) };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Finds documents with pagination support.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find documents.\n * @param options - Pagination options including page, limit, and population.\n * @returns A promise that resolves to a standardized response with paginated results.\n */\n async findPaging(\n filter: T_QueryFilter<T> = {},\n options: I_PaginateOptionsWithPopulate = {},\n ): Promise<I_Return<T_PaginateResult<T>>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const filteredOptions = { ...options };\n\n if (options.populate) {\n filteredOptions.populate = filterDynamicVirtualsFromPopulate(options.populate, dynamicVirtuals);\n }\n\n const result = await this.model.paginate(normalizedFilter, filteredOptions);\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0) {\n const populatedDocs = await this.populateDynamicVirtualsForDocuments(result.docs, options.populate);\n\n return { success: true, result: { ...result, docs: populatedDocs.map(item => toPlainObject(item)) } };\n }\n\n return { success: true, result: { ...result, docs: result.docs.map(item => toPlainObject(item)) } };\n }\n catch (error) {\n return catchError<T_PaginateResult<T>>(error);\n }\n }\n\n /**\n * Performs aggregation with pagination support.\n *\n * @param pipeline - The aggregation pipeline stages.\n * @param options - Pagination options for the aggregation result.\n * @returns A promise that resolves to a standardized response with paginated aggregation results.\n */\n async findPagingAggregate(\n pipeline: T_PipelineStage[],\n options: I_PaginateOptionsWithPopulate = {},\n ): Promise<I_Return<T_AggregatePaginateResult<T>>> {\n try {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const filteredOptions = { ...options };\n\n if (options.populate) {\n filteredOptions.populate = filterDynamicVirtualsFromPopulate(options.populate, dynamicVirtuals);\n }\n\n const result = await this.model.aggregatePaginate(\n this.model.aggregate(pipeline),\n filteredOptions,\n );\n\n const finalDocs = await this.populateDynamicVirtualsForDocuments(result.docs, options.populate);\n\n return { success: true, result: { ...result, docs: finalDocs.map(item => item?.toObject?.() ?? item) } };\n }\n catch (error) {\n return catchError<T_AggregatePaginateResult<T>>(error);\n }\n }\n\n /**\n * Counts documents matching the filter criteria.\n *\n * @param filter - The filter criteria to count documents.\n * @returns A promise that resolves to a standardized response with the document count.\n */\n async count(filter: T_QueryFilter<T> = {}): Promise<I_Return<number>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model.countDocuments(normalizedFilter);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<number>(error);\n }\n }\n\n /**\n * Creates a single document.\n *\n * @param doc - The document to create.\n * @returns A promise that resolves to a standardized response with the created document.\n */\n async createOne(doc: T | Partial<T>): Promise<I_Return<T>> {\n try {\n const result = await this.model.create(doc as unknown as Parameters<typeof this.model.create>[0]);\n\n return { success: true, result: (result as T)?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Creates multiple documents with bulk insertion.\n *\n * @param docs - An array of documents to create.\n * @param options - Options for the bulk insertion operation.\n * @returns A promise that resolves to a standardized response with the created documents.\n */\n async createMany(\n docs: (T | Partial<T>)[],\n options: T_InsertManyOptions = {},\n ): Promise<I_Return<T[]>> {\n try {\n const createdDocuments = await this.model.insertMany(docs, options);\n\n return { success: true, result: createdDocuments.map(item => item?.toObject?.() ?? item) as T[] };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Updates a single document and returns the updated version.\n *\n * @param filter - The filter criteria to find the document to update.\n * @param update - The update data to apply.\n * @param options - Options for the update operation.\n * @returns A promise that resolves to a standardized response with the updated document.\n */\n async updateOne(\n filter: T_QueryFilter<T> = {},\n update: T_UpdateQuery<T> = {},\n options: I_UpdateOptionsExtended = {},\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .findOneAndUpdate(normalizedFilter, update, {\n new: true,\n ...options,\n })\n .exec();\n\n if (!result) {\n return {\n success: false,\n message: `Failed to update ${this.getModelName()}.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result: result?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Updates multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to update.\n * @param update - The update data to apply.\n * @param options - Options for the update operation.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateMany(\n filter: T_QueryFilter<T> = {},\n update: T_UpdateQuery<T> = {},\n options: I_UpdateOptionsExtended = {},\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .updateMany(normalizedFilter, update, options)\n .exec();\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Deletes a single document and returns the deleted version.\n *\n * @param filter - The filter criteria to find the document to delete.\n * @param options - Options for the delete operation.\n * @returns A promise that resolves to a standardized response with the deleted document.\n */\n async deleteOne(\n filter: T_QueryFilter<T> = {},\n options: I_DeleteOptionsExtended = {},\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .findOneAndDelete(normalizedFilter, options)\n .exec();\n\n if (!result) {\n return {\n success: false,\n message: `No ${this.getModelName()} found to delete.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result: result?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Deletes multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to delete.\n * @param options - Options for the delete operation.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteMany(\n filter: T_QueryFilter<T> = {},\n options: I_DeleteOptionsExtended = {},\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model.deleteMany(normalizedFilter, options).exec();\n\n if (result.deletedCount === 0) {\n return {\n success: false,\n message: `No documents found to delete.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n\n /**\n * Creates a unique short ID based on a given ID.\n * This method generates multiple short IDs with increasing lengths and finds the first available one.\n *\n * @param id - The base ID to generate short IDs from.\n * @param length - The initial length for short ID generation (default: 4).\n * @returns A promise that resolves to a standardized response with the unique short ID.\n */\n async createShortId(id: string, length = 4): Promise<I_Return<string>> {\n try {\n const maxRetries = 10;\n const shortIds = Array.from({ length: maxRetries }, (_, index) =>\n generateShortId(id, index + length));\n\n // Use a single $in query instead of 10 parallel exists() calls\n const existingDocs = await this.model\n .find({ shortId: { $in: shortIds } })\n .select('shortId')\n .lean();\n\n const existingShortIds = new Set(\n existingDocs.map((d: Record<string, unknown>) => d['shortId'] as string),\n );\n\n const availableShortId = shortIds.find(s => !existingShortIds.has(s));\n\n if (availableShortId) {\n return { success: true, result: availableShortId };\n }\n\n return {\n success: false,\n message: 'Failed to create a unique shortId',\n code: RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE,\n };\n }\n catch (error) {\n return catchError<string>(error);\n }\n }\n\n /**\n * Creates a query for slug existence checking.\n * This method generates a query that checks for slug existence in both current and historical slug fields.\n *\n * @param options - Configuration for slug query generation including slug, field, and filter.\n * @param options.slug - The slug string to check for existence.\n * @param options.field - The field name for object-based slug checking.\n * @param options.isObject - Whether the slug is stored as an object with nested fields.\n * @param options.haveHistory - Whether to check historical slug fields for existence.\n * @param options.filter - Additional filter conditions to apply to the query.\n * @returns A MongoDB query object for checking slug existence.\n */\n createSlugQuery({ slug, field, isObject, haveHistory = false, filter }: I_Input_GenerateSlug<T>) {\n const baseFilter = { ...(filter ?? {}) };\n\n return isObject\n ? {\n ...baseFilter,\n $or: [\n { [`slug.${field}`]: slug },\n ...(haveHistory ? [{ slugHistory: { $elemMatch: { [`slug.${field}`]: slug } } }] : []),\n ],\n }\n : {\n ...baseFilter,\n $or: [\n { slug },\n ...(haveHistory ? [{ slugHistory: slug }] : []),\n ],\n };\n }\n\n /**\n * Creates a unique slug based on a given string.\n * This method generates multiple slug variations and finds the first available one.\n *\n * @param options - Configuration for slug generation including slug, field, and filter.\n * @param options.slug - The base slug string to make unique.\n * @param options.field - The field name for object-based slug checking.\n * @param options.isObject - Whether the slug is stored as an object with nested fields.\n * @param options.haveHistory - Whether to check historical slug fields for uniqueness.\n * @param options.filter - Additional filter conditions to apply when checking slug existence.\n * @returns A promise that resolves to a unique slug string.\n */\n async createUniqueSlug({ slug, field, isObject, haveHistory, filter }: I_Input_GenerateSlug<T>): Promise<string> {\n if (!slug || typeof slug !== 'string') {\n throw new Error('Invalid slug provided: must be a non-empty string');\n }\n\n const baseSlug = generateSlug(slug);\n\n const baseExists = await this.model.exists(\n this.createSlugQuery({ slug: baseSlug, field, isObject, haveHistory, filter }),\n );\n\n if (!baseExists) {\n return baseSlug;\n }\n\n // Batch query: check all slug variations in a single database call instead of N+1 sequential queries\n const variants = Array.from(\n { length: MONGO_SLUG_MAX_ATTEMPTS },\n (_, i) => `${baseSlug}-${i + 1}`,\n );\n\n const slugQueries = variants.map(s =>\n this.createSlugQuery({ slug: s, field, isObject, haveHistory, filter }),\n );\n\n const slugField = isObject ? `slug.${field as string}` : 'slug';\n const existingDocs = await this.model\n .find({ $or: slugQueries.map(q => q.$or).flat() })\n .select(slugField)\n .lean();\n\n const existingSlugs = new Set(\n existingDocs.map((d: Record<string, unknown>) => {\n if (isObject) {\n const slug = d['slug'] as Record<string, unknown> | undefined;\n return slug?.[field as string];\n }\n return d['slug'];\n }),\n );\n\n const available = variants.find(s => !existingSlugs.has(s));\n\n if (available) {\n return available;\n }\n\n const timestamp = Date.now();\n const randomSuffix = generateRandomString(6);\n\n return `${baseSlug}-${timestamp}-${randomSuffix}`;\n }\n\n /**\n * Creates a slug for a document field.\n * This method handles both simple string fields and object fields with nested slug generation.\n *\n * @param options - Configuration for slug creation including field, source document, and filter.\n * @param options.field - The field name to create a slug for.\n * @param options.from - The source document containing the field value.\n * @param options.haveHistory - Whether to check historical slug fields for uniqueness.\n * @param options.filter - Additional filter conditions to apply when checking slug existence.\n * @returns A promise that resolves to a standardized response with the created slug(s).\n */\n async createSlug<R = string>({ field, from, filter, haveHistory }: I_Input_CreateSlug<T>): Promise<I_Return<R>> {\n try {\n const fieldValue = from[field as keyof T];\n const isObjectValue = isObject(fieldValue);\n\n if (isObjectValue) {\n const uniqueSlug = Object.fromEntries(\n await Promise.all(\n Object.entries(fieldValue).map(async ([key, value]) => {\n const uniqueSlugForKey = await this.createUniqueSlug({\n slug: value as string,\n field: key,\n isObject: true,\n haveHistory,\n filter,\n });\n return [key, uniqueSlugForKey];\n }),\n ),\n );\n\n return { success: true, result: uniqueSlug as R };\n }\n\n const uniqueSlug = await this.createUniqueSlug({\n slug: fieldValue as string,\n field,\n isObject: false,\n haveHistory,\n filter,\n });\n\n return { success: true, result: uniqueSlug as R };\n }\n catch (error) {\n return catchError<R>(error);\n }\n }\n\n /**\n * Checks if a slug already exists in the collection.\n * This method verifies slug existence in both current and historical slug fields.\n *\n * @param options - Configuration for slug checking including slug, field, source document, and filter.\n * @param options.slug - The slug string to check for existence.\n * @param options.field - The field name for object-based slug checking.\n * @param options.from - The source document containing the field value.\n * @param options.haveHistory - Whether to check historical slug fields for existence.\n * @param options.filter - Additional filter conditions to apply to the query.\n * @returns A promise that resolves to a standardized response indicating whether the slug exists.\n */\n async checkSlug({ slug, field, from, filter, haveHistory }: I_Input_CheckSlug<T>): Promise<I_Return<boolean>> {\n try {\n const fieldValue = from[field as keyof T];\n const isObjectValue = isObject(fieldValue);\n\n if (isObjectValue) {\n const values = Object.values(fieldValue);\n const nestedSlugs = values.map(value => generateSlug(value as string));\n\n const existenceChecks = await Promise.all(\n nestedSlugs.map(nestedSlug =>\n this.model.exists(this.createSlugQuery({\n slug: nestedSlug,\n field,\n isObject: true,\n haveHistory,\n filter,\n })),\n ),\n );\n\n if (existenceChecks.some(exists => exists)) {\n return { success: true, result: true };\n }\n\n return { success: true, result: false };\n }\n\n const baseSlug = generateSlug(slug);\n const exists = await this.model.exists(this.createSlugQuery({\n slug: baseSlug,\n field,\n isObject: false,\n filter,\n }));\n\n return { success: true, result: exists !== null };\n }\n catch (error) {\n return catchError<boolean>(error);\n }\n }\n\n /**\n * Performs aggregation operations on the collection.\n *\n * @param pipeline - The aggregation pipeline stages to execute.\n * @returns A promise that resolves to a standardized response with the aggregation results.\n */\n async aggregate(pipeline: T_PipelineStage[]): Promise<I_Return<T[]>> {\n try {\n const result = await this.model.aggregate<T>(pipeline);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Retrieves distinct values for the specified key from the collection.\n *\n * @param key - The field for which to return distinct values.\n * @param filter - The filter query to apply (optional).\n * @param options - Additional options for the distinct operation (optional).\n * @returns A promise that resolves to a standardized response with the array of distinct values.\n */\n async distinct(\n key: string,\n filter: T_QueryFilter<T> = {},\n options: T_QueryOptions<T> = {},\n ): Promise<I_Return<unknown[]>> {\n try {\n const result = await this.model.distinct(key, filter, options);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<unknown[]>(error);\n }\n }\n}\n"],"mappings":";;;;;;;AAmBA,SAAS,EAAiB,GAAW;AACjC,QAAQ,GAAoC,YAAY,IAAI;;AAchE,IAAa,IAAb,MAA+D;CAC3D;CASA,YAAY,GAAmC,GAAqC;AAChF,EADgB,KAAA,QAAA,GAChB,KAAK,eAAe,GAAS,gBAAgB;;C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MAAM,UAAU,EAAE,SAAM,UAAO,SAAM,WAAQ,kBAAiE;AAC1G,MAAI;GACA,IAAM,IAAa,EAAK;AAGxB,OAFsB,EAAS,EAAW,EAEvB;IAEf,IAAM,IADS,OAAO,OAAO,EAAW,CACb,KAAI,MAAS,EAAa,EAAgB,CAAC;AAkBtE,YAhBwB,MAAM,QAAQ,IAClC,EAAY,KAAI,MACZ,KAAK,MAAM,OAAO,KAAK,gBAAgB;KACnC,MAAM;KACN;KACA,UAAU;KACV;KACA;KACH,CAAC,CAAC,CACN,CACJ,EAEmB,MAAK,MAAU,EAAO,GAC/B;KAAE,SAAS;KAAM,QAAQ;KAAM,GAGnC;KAAE,SAAS;KAAM,QAAQ;KAAO;;GAG3C,IAAM,IAAW,EAAa,EAAK;AAQnC,UAAO;IAAE,SAAS;IAAM,QAPT,MAAM,KAAK,MAAM,OAAO,KAAK,gBAAgB;KACxD,MAAM;KACN;KACA,UAAU;KACV;KACH,CAAC,CAAC,KAEwC;IAAM;WAE9C,GAAO;AACV,UAAO,EAAoB,EAAM;;;CAUzC,MAAM,UAAU,GAAqD;AACjE,MAAI;AAGA,UAAO;IAAE,SAAS;IAAM,QAFT,MAAM,KAAK,MAAM,UAAa,EAAS;IAEtB;WAE7B,GAAO;AACV,UAAO,EAAgB,EAAM;;;CAYrC,MAAM,SACF,GACA,IAA2B,EAAE,EAC7B,IAA6B,EAAE,EACH;AAC5B,MAAI;AAGA,UAAO;IAAE,SAAS;IAAM,QAFT,MAAM,KAAK,MAAM,SAAS,GAAK,GAAQ,EAAQ;IAE9B;WAE7B,GAAO;AACV,UAAO,EAAsB,EAAM"}
@@ -4,16 +4,24 @@ import { C_Db, C_Document, T_DeleteResult, T_Filter, T_UpdateResult, T_WithId }
4
4
  * MongoDB native driver controller for direct database operations.
5
5
  * This class provides a simplified interface for MongoDB operations using the native driver,
6
6
  * with automatic generic field generation and standardized response formatting.
7
+ *
8
+ * @see I_MongoController for the shared polymorphic interface (use via type assertion when needed).
7
9
  */
8
10
  export declare class MongoController<D extends Partial<C_Document>> {
9
11
  private collection;
12
+ private defaultLimit;
13
+ private collectionName;
10
14
  /**
11
15
  * Creates a new MongoDB controller instance.
12
16
  *
13
17
  * @param db - The MongoDB database instance.
14
18
  * @param collectionName - The name of the collection to operate on.
19
+ * @param options - Optional configuration for the controller.
20
+ * @param options.defaultLimit - Maximum documents returned by findAll when no limit is specified (default: 10,000).
15
21
  */
16
- constructor(db: C_Db, collectionName: string);
22
+ constructor(db: C_Db, collectionName: string, options?: {
23
+ defaultLimit?: number;
24
+ });
17
25
  /**
18
26
  * Creates a single document in the collection.
19
27
  * This method adds generic fields (id, isDel, timestamps) to the document before insertion.
@@ -1,17 +1,19 @@
1
1
  import { RESPONSE_STATUS as e } from "../../constant/response-status.js";
2
- import { catchError as t } from "../log/log.util.js";
3
- import { mongo as n } from "./mongo.util.js";
2
+ import { catchError as t, log as n } from "../log/log.util.js";
3
+ import { mongo as r } from "./mongo.util.js";
4
4
  //#region src/node/mongo/mongo.controller.native.ts
5
- var r = class {
5
+ var i = class {
6
6
  collection;
7
- constructor(e, t) {
8
- this.collection = e.collection(t);
7
+ defaultLimit;
8
+ collectionName;
9
+ constructor(e, t, n) {
10
+ this.collection = e.collection(t), this.collectionName = t, this.defaultLimit = n?.defaultLimit ?? 1e4;
9
11
  }
10
- async createOne(r) {
12
+ async createOne(n) {
11
13
  try {
12
14
  let t = {
13
- ...n.createGenericFields(),
14
- ...r
15
+ ...r.createGenericFields(),
16
+ ...n
15
17
  };
16
18
  return (await this.collection.insertOne(t)).acknowledged ? {
17
19
  success: !0,
@@ -26,10 +28,10 @@ var r = class {
26
28
  return t(e);
27
29
  }
28
30
  }
29
- async createMany(r) {
31
+ async createMany(n) {
30
32
  try {
31
- let t = r.map((e) => ({
32
- ...n.createGenericFields(),
33
+ let t = n.map((e) => ({
34
+ ...r.createGenericFields(),
33
35
  ...e
34
36
  })), i = await this.collection.insertMany(t);
35
37
  return i.insertedCount === 0 ? {
@@ -63,10 +65,11 @@ var r = class {
63
65
  }
64
66
  async findAll(e = {}) {
65
67
  try {
66
- return {
68
+ let t = await this.collection.find(e).limit(this.defaultLimit).maxTimeMS(3e4).toArray();
69
+ return t.length === this.defaultLimit && n.warn(`[${this.collectionName}] findAll returned exactly ${this.defaultLimit} documents (the default limit). Results may be truncated. Consider using pagination or setting an explicit limit.`), {
67
70
  success: !0,
68
71
  message: "Documents retrieved successfully",
69
- result: await this.collection.find(e).limit(1e4).maxTimeMS(3e4).toArray()
72
+ result: t
70
73
  };
71
74
  } catch (e) {
72
75
  return t(e);
@@ -150,6 +153,6 @@ var r = class {
150
153
  }
151
154
  };
152
155
  //#endregion
153
- export { r as MongoController };
156
+ export { i as MongoController };
154
157
 
155
158
  //# sourceMappingURL=mongo.controller.native.js.map