@cyberskill/shared 3.12.0 → 3.14.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 (254) hide show
  1. package/dist/config/commitlint/index.d.ts +5 -1
  2. package/dist/{src/config → config}/config.type.d.ts +1 -1
  3. package/dist/{src/config → config}/config.util.d.ts +1 -1
  4. package/dist/{src/config → config}/env/env.util.d.ts +5 -0
  5. package/dist/config/env/env.util.js +20 -16
  6. package/dist/config/env/env.util.js.map +1 -1
  7. package/dist/config/env/index.d.ts +3 -1
  8. package/dist/config/env/index.js +2 -2
  9. package/dist/config/eslint/index.d.ts +1198 -1
  10. package/dist/config/graphql-codegen/index.d.ts +2 -1
  11. package/dist/config/index.d.ts +2 -1
  12. package/dist/config/lint-staged/index.d.ts +5 -1
  13. package/dist/config/storybook/index.d.ts +2 -1
  14. package/dist/config/vitest/index.d.ts +3 -1
  15. package/dist/config/vitest/vitest.e2e.d.ts +20 -1
  16. package/dist/config/vitest/vitest.e2e.js +4 -4
  17. package/dist/config/vitest/vitest.e2e.js.map +1 -1
  18. package/dist/config/vitest/vitest.unit.d.ts +22 -1
  19. package/dist/config/vitest/vitest.unit.js +5 -5
  20. package/dist/config/vitest/vitest.unit.js.map +1 -1
  21. package/dist/config/vitest/vitest.unit.setup.js +10 -0
  22. package/dist/config/vitest/vitest.unit.setup.js.map +1 -0
  23. package/dist/constant/index.d.ts +5 -1
  24. package/dist/node/apollo-server/apollo-server.type.d.ts +20 -0
  25. package/dist/{src/node → node}/apollo-server/apollo-server.util.d.ts +1 -0
  26. package/dist/node/apollo-server/apollo-server.util.js +40 -16
  27. package/dist/node/apollo-server/apollo-server.util.js.map +1 -1
  28. package/dist/node/apollo-server/index.d.ts +2 -1
  29. package/dist/node/cli/index.d.ts +2 -1
  30. package/dist/node/cli/index.js +26 -28
  31. package/dist/node/cli/index.js.map +1 -1
  32. package/dist/{src/node → node}/command/command.util.d.ts +5 -0
  33. package/dist/node/command/command.util.js +49 -48
  34. package/dist/node/command/command.util.js.map +1 -1
  35. package/dist/node/command/index.d.ts +2 -1
  36. package/dist/node/command/index.js +2 -2
  37. package/dist/{src/node → node}/express/express.type.d.ts +11 -0
  38. package/dist/{src/node → node}/express/express.util.d.ts +34 -6
  39. package/dist/node/express/express.util.js +81 -56
  40. package/dist/node/express/express.util.js.map +1 -1
  41. package/dist/node/express/index.d.ts +2 -1
  42. package/dist/node/express/index.js +2 -2
  43. package/dist/node/fs/index.d.ts +2 -1
  44. package/dist/node/log/index.d.ts +2 -1
  45. package/dist/node/log/log.type.d.ts +46 -0
  46. package/dist/node/log/log.type.js.map +1 -1
  47. package/dist/{src/node → node}/log/log.util.d.ts +1 -1
  48. package/dist/node/log/log.util.js +25 -11
  49. package/dist/node/log/log.util.js.map +1 -1
  50. package/dist/node/mongo/index.d.ts +7 -1
  51. package/dist/node/mongo/index.js +7 -8
  52. package/dist/{src/node → node}/mongo/mongo.constant.d.ts +5 -0
  53. package/dist/node/mongo/mongo.constant.js +2 -2
  54. package/dist/node/mongo/mongo.constant.js.map +1 -1
  55. package/dist/{src/node → node}/mongo/mongo.controller.helpers.d.ts +1 -1
  56. package/dist/{src/node → node}/mongo/mongo.controller.mongoose.d.ts +4 -1
  57. package/dist/node/mongo/mongo.controller.mongoose.js +41 -55
  58. package/dist/node/mongo/mongo.controller.mongoose.js.map +1 -1
  59. package/dist/{src/node → node}/mongo/mongo.controller.native.d.ts +30 -3
  60. package/dist/node/mongo/mongo.controller.native.js +31 -14
  61. package/dist/node/mongo/mongo.controller.native.js.map +1 -1
  62. package/dist/{src/node → node}/mongo/mongo.controller.type.d.ts +1 -1
  63. package/dist/{src/node → node}/mongo/mongo.type.d.ts +3 -1
  64. package/dist/{src/node → node}/mongo/mongo.util.d.ts +1 -0
  65. package/dist/node/mongo/mongo.util.js +38 -17
  66. package/dist/node/mongo/mongo.util.js.map +1 -1
  67. package/dist/node/package/index.d.ts +2 -1
  68. package/dist/{src/node → node}/package/package.util.d.ts +1 -1
  69. package/dist/node/package/package.util.js +47 -47
  70. package/dist/node/path/index.d.ts +2 -1
  71. package/dist/node/path/index.js +2 -2
  72. package/dist/{src/node → node}/path/path.constant.d.ts +4 -0
  73. package/dist/node/path/path.constant.js +75 -72
  74. package/dist/node/path/path.constant.js.map +1 -1
  75. package/dist/node/storage/index.d.ts +3 -1
  76. package/dist/{src/node → node}/storage/storage.util.d.ts +50 -1
  77. package/dist/node/storage/storage.util.js +79 -54
  78. package/dist/node/storage/storage.util.js.map +1 -1
  79. package/dist/node/upload/index.d.ts +3 -1
  80. package/dist/{src/node → node}/upload/upload.type.d.ts +2 -0
  81. package/dist/node/upload/upload.type.js.map +1 -1
  82. package/dist/{src/node → node}/upload/upload.util.d.ts +2 -1
  83. package/dist/node/upload/upload.util.js +62 -52
  84. package/dist/node/upload/upload.util.js.map +1 -1
  85. package/dist/node/ws/index.d.ts +2 -1
  86. package/dist/{src/node → node}/ws/ws.util.d.ts +7 -0
  87. package/dist/node/ws/ws.util.js +20 -19
  88. package/dist/node/ws/ws.util.js.map +1 -1
  89. package/dist/react/apollo-client/apollo-client.component.js.map +1 -1
  90. package/dist/{src/react → react}/apollo-client/apollo-client.type.d.ts +3 -1
  91. package/dist/react/apollo-client/apollo-client.util.js +6 -6
  92. package/dist/react/apollo-client/apollo-client.util.js.map +1 -1
  93. package/dist/react/apollo-client/index.d.ts +9 -1
  94. package/dist/react/apollo-client/links/index.d.ts +1 -1
  95. package/dist/react/apollo-client-nextjs/apollo-client-nextjs.rsc.d.ts +16 -1
  96. package/dist/react/apollo-client-nextjs/index.d.ts +2 -1
  97. package/dist/react/apollo-error/apollo-error.component.js +1 -1
  98. package/dist/react/apollo-error/apollo-error.component.js.map +1 -1
  99. package/dist/react/apollo-error/apollo-error.util.js.map +1 -1
  100. package/dist/react/apollo-error/index.d.ts +6 -1
  101. package/dist/react/i18next/i18next.server.d.ts +17 -0
  102. package/dist/react/i18next/i18next.server.js +9 -0
  103. package/dist/react/i18next/i18next.server.js.map +1 -0
  104. package/dist/react/i18next/index.d.ts +2 -1
  105. package/dist/react/loading/index.d.ts +5 -1
  106. package/dist/{src/react → react}/loading/loading.provider.d.ts +1 -1
  107. package/dist/react/log/index.d.ts +2 -1
  108. package/dist/react/log/log.type.d.ts +1 -0
  109. package/dist/{src/react → react}/log/log.util.d.ts +1 -1
  110. package/dist/react/next-intl/index.d.ts +6 -1
  111. package/dist/{src/react → react}/next-intl/next-intl.hoc.d.ts +5 -9
  112. package/dist/react/next-intl/next-intl.hoc.js +14 -10
  113. package/dist/react/next-intl/next-intl.hoc.js.map +1 -1
  114. package/dist/react/next-intl/next-intl.server.d.ts +10 -0
  115. package/dist/react/next-intl/next-intl.server.js +7 -0
  116. package/dist/react/next-intl/next-intl.server.js.map +1 -0
  117. package/dist/{src/react → react}/next-intl/next-intl.type.d.ts +1 -1
  118. package/dist/react/storage/index.d.ts +2 -1
  119. package/dist/{src/react → react}/storage/storage.hook.d.ts +1 -1
  120. package/dist/{src/react → react}/storage/storage.util.d.ts +34 -1
  121. package/dist/react/storage/storage.util.js +30 -5
  122. package/dist/react/storage/storage.util.js.map +1 -1
  123. package/dist/react/toast/index.d.ts +1 -1
  124. package/dist/react/userback/index.d.ts +2 -1
  125. package/dist/react/userback/userback.component.js.map +1 -1
  126. package/dist/{src/typescript → typescript}/common.type.d.ts +4 -0
  127. package/dist/typescript/common.type.js +2 -2
  128. package/dist/typescript/common.type.js.map +1 -1
  129. package/dist/typescript/index.d.ts +5 -1
  130. package/dist/typescript/index.js +2 -2
  131. package/dist/util/common/index.d.ts +5 -1
  132. package/dist/util/index.d.ts +9 -1
  133. package/dist/util/log/index.d.ts +2 -1
  134. package/dist/{src/util → util}/log/log.util.d.ts +1 -1
  135. package/dist/util/object/index.d.ts +4 -1
  136. package/dist/util/object/object.util.js +29 -18
  137. package/dist/util/object/object.util.js.map +1 -1
  138. package/dist/util/serializer/index.d.ts +2 -1
  139. package/dist/{src/util → util}/serializer/serializer.util.d.ts +8 -0
  140. package/dist/util/serializer/serializer.util.js +51 -64
  141. package/dist/util/serializer/serializer.util.js.map +1 -1
  142. package/dist/util/storage/storage-envelope.d.ts +25 -0
  143. package/dist/util/storage/storage-envelope.js +18 -0
  144. package/dist/util/storage/storage-envelope.js.map +1 -0
  145. package/dist/util/string/index.d.ts +5 -1
  146. package/dist/util/validate/index.d.ts +4 -1
  147. package/package.json +33 -12
  148. package/dist/node/mongo/mongo.type.js +0 -8
  149. package/dist/node/mongo/mongo.type.js.map +0 -1
  150. package/dist/node_modules/.pnpm/vitest@4.1.2_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.3_@types_nod_0827261ede788764a5d99ac6bdf44bde/node_modules/vitest/dist/config.js +0 -8
  151. package/dist/node_modules/.pnpm/vitest@4.1.2_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.3_@types_nod_0827261ede788764a5d99ac6bdf44bde/node_modules/vitest/dist/config.js.map +0 -1
  152. package/dist/src/config/commitlint/index.d.ts +0 -5
  153. package/dist/src/config/env/index.d.ts +0 -3
  154. package/dist/src/config/eslint/index.d.ts +0 -1198
  155. package/dist/src/config/graphql-codegen/index.d.ts +0 -2
  156. package/dist/src/config/index.d.ts +0 -2
  157. package/dist/src/config/lint-staged/index.d.ts +0 -5
  158. package/dist/src/config/storybook/index.d.ts +0 -2
  159. package/dist/src/config/vitest/index.d.ts +0 -3
  160. package/dist/src/config/vitest/vitest.e2e.d.ts +0 -20
  161. package/dist/src/config/vitest/vitest.unit.d.ts +0 -22
  162. package/dist/src/constant/index.d.ts +0 -5
  163. package/dist/src/node/apollo-server/apollo-server.type.d.ts +0 -8
  164. package/dist/src/node/apollo-server/index.d.ts +0 -2
  165. package/dist/src/node/cli/index.d.ts +0 -2
  166. package/dist/src/node/command/index.d.ts +0 -2
  167. package/dist/src/node/express/index.d.ts +0 -2
  168. package/dist/src/node/fs/index.d.ts +0 -2
  169. package/dist/src/node/log/index.d.ts +0 -2
  170. package/dist/src/node/log/log.type.d.ts +0 -29
  171. package/dist/src/node/mongo/index.d.ts +0 -6
  172. package/dist/src/node/package/index.d.ts +0 -2
  173. package/dist/src/node/path/index.d.ts +0 -2
  174. package/dist/src/node/storage/index.d.ts +0 -3
  175. package/dist/src/node/upload/index.d.ts +0 -3
  176. package/dist/src/node/ws/index.d.ts +0 -2
  177. package/dist/src/react/apollo-client/index.d.ts +0 -9
  178. package/dist/src/react/apollo-client/links/index.d.ts +0 -1
  179. package/dist/src/react/apollo-client-nextjs/apollo-client-nextjs.rsc.d.ts +0 -16
  180. package/dist/src/react/apollo-client-nextjs/index.d.ts +0 -2
  181. package/dist/src/react/apollo-error/index.d.ts +0 -6
  182. package/dist/src/react/i18next/index.d.ts +0 -2
  183. package/dist/src/react/loading/index.d.ts +0 -5
  184. package/dist/src/react/log/index.d.ts +0 -2
  185. package/dist/src/react/log/log.type.d.ts +0 -1
  186. package/dist/src/react/next-intl/index.d.ts +0 -6
  187. package/dist/src/react/storage/index.d.ts +0 -2
  188. package/dist/src/react/toast/index.d.ts +0 -1
  189. package/dist/src/react/userback/index.d.ts +0 -2
  190. package/dist/src/typescript/index.d.ts +0 -5
  191. package/dist/src/util/common/index.d.ts +0 -5
  192. package/dist/src/util/index.d.ts +0 -9
  193. package/dist/src/util/log/index.d.ts +0 -2
  194. package/dist/src/util/object/index.d.ts +0 -4
  195. package/dist/src/util/serializer/index.d.ts +0 -2
  196. package/dist/src/util/string/index.d.ts +0 -5
  197. package/dist/src/util/validate/index.d.ts +0 -4
  198. /package/dist/{src/config → config}/env/env.constant.d.ts +0 -0
  199. /package/dist/{src/config → config}/env/env.type.d.ts +0 -0
  200. /package/dist/{src/config → config}/graphql-codegen/graphql-codegen.type.d.ts +0 -0
  201. /package/dist/{src/config → config}/graphql-codegen/graphql-codegen.util.d.ts +0 -0
  202. /package/dist/{src/config → config}/storybook/storybook.main.d.ts +0 -0
  203. /package/dist/{src/config → config}/storybook/storybook.preview.d.ts +0 -0
  204. /package/dist/{src/config → config}/vitest/vitest.unit.setup.d.ts +0 -0
  205. /package/dist/{src/constant → constant}/common.d.ts +0 -0
  206. /package/dist/{src/constant → constant}/response-status.d.ts +0 -0
  207. /package/dist/{src/node → node}/command/command.type.d.ts +0 -0
  208. /package/dist/{src/node → node}/fs/fs.type.d.ts +0 -0
  209. /package/dist/{src/node → node}/fs/fs.util.d.ts +0 -0
  210. /package/dist/{src/node → node}/mongo/mongo.controller.d.ts +0 -0
  211. /package/dist/{src/node → node}/mongo/mongo.dynamic-populate.d.ts +0 -0
  212. /package/dist/{src/node → node}/mongo/mongo.internal-types.d.ts +0 -0
  213. /package/dist/{src/node → node}/mongo/mongo.populate.d.ts +0 -0
  214. /package/dist/{src/node → node}/package/package.type.d.ts +0 -0
  215. /package/dist/{src/node → node}/path/path.util.d.ts +0 -0
  216. /package/dist/{src/node → node}/storage/storage.constant.d.ts +0 -0
  217. /package/dist/{src/node → node}/storage/storage.type.d.ts +0 -0
  218. /package/dist/{src/node → node}/upload/upload.constant.d.ts +0 -0
  219. /package/dist/{src/node → node}/ws/ws.type.d.ts +0 -0
  220. /package/dist/{src/react → react}/apollo-client/apollo-client.component.d.ts +0 -0
  221. /package/dist/{src/react → react}/apollo-client/apollo-client.constant.d.ts +0 -0
  222. /package/dist/{src/react → react}/apollo-client/apollo-client.context.d.ts +0 -0
  223. /package/dist/{src/react → react}/apollo-client/apollo-client.hook.d.ts +0 -0
  224. /package/dist/{src/react → react}/apollo-client/apollo-client.util.d.ts +0 -0
  225. /package/dist/{src/react → react}/apollo-client/links/upload.d.ts +0 -0
  226. /package/dist/{src/react → react}/apollo-client-nextjs/apollo-client-nextjs.component.d.ts +0 -0
  227. /package/dist/{src/react → react}/apollo-client-nextjs/apollo-client-nextjs.util.d.ts +0 -0
  228. /package/dist/{src/react → react}/apollo-error/apollo-error.component.d.ts +0 -0
  229. /package/dist/{src/react → react}/apollo-error/apollo-error.context.d.ts +0 -0
  230. /package/dist/{src/react → react}/apollo-error/apollo-error.hook.d.ts +0 -0
  231. /package/dist/{src/react → react}/apollo-error/apollo-error.provider.d.ts +0 -0
  232. /package/dist/{src/react → react}/apollo-error/apollo-error.type.d.ts +0 -0
  233. /package/dist/{src/react → react}/apollo-error/apollo-error.util.d.ts +0 -0
  234. /package/dist/{src/react → react}/i18next/i18next.hook.d.ts +0 -0
  235. /package/dist/{src/react → react}/i18next/i18next.util.d.ts +0 -0
  236. /package/dist/{src/react → react}/loading/loading.component.d.ts +0 -0
  237. /package/dist/{src/react → react}/loading/loading.context.d.ts +0 -0
  238. /package/dist/{src/react → react}/loading/loading.hook.d.ts +0 -0
  239. /package/dist/{src/react → react}/loading/loading.type.d.ts +0 -0
  240. /package/dist/{src/react → react}/next-intl/next-intl.constant.d.ts +0 -0
  241. /package/dist/{src/react → react}/next-intl/next-intl.context.d.ts +0 -0
  242. /package/dist/{src/react → react}/next-intl/next-intl.hook.d.ts +0 -0
  243. /package/dist/{src/react → react}/next-intl/next-intl.provider.d.ts +0 -0
  244. /package/dist/{src/react → react}/userback/userback.component.d.ts +0 -0
  245. /package/dist/{src/react → react}/userback/userback.type.d.ts +0 -0
  246. /package/dist/{src/typescript → typescript}/react.type.d.ts +0 -0
  247. /package/dist/{src/util → util}/common/common.type.d.ts +0 -0
  248. /package/dist/{src/util → util}/common/common.util.d.ts +0 -0
  249. /package/dist/{src/util → util}/log/log.type.d.ts +0 -0
  250. /package/dist/{src/util → util}/object/object.util.d.ts +0 -0
  251. /package/dist/{src/util → util}/serializer/serializer.type.d.ts +0 -0
  252. /package/dist/{src/util → util}/string/string.type.d.ts +0 -0
  253. /package/dist/{src/util → util}/string/string.util.d.ts +0 -0
  254. /package/dist/{src/util → util}/validate/validate.util.d.ts +0 -0
@@ -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 { isObject } from '#util/common/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, populateDynamicVirtuals } from './mongo.dynamic-populate.js';\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: 1,000).\n */\n constructor(private model: I_ExtendedModel<T>, options?: { defaultLimit?: number }) {\n this.defaultLimit = options?.defaultLimit ?? 1_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 populated = await this.populateDynamic([result], populate);\n return populated[0] ?? 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 return this.populateDynamic(results, populate);\n }\n\n /**\n * Internal helper that populates dynamic virtuals for an array of documents.\n * Shared implementation used by both single-document and multi-document methods.\n */\n private async populateDynamic(results: T[], populate?: T_Input_Populate): Promise<T[]> {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0 && results.length > 0) {\n return await populateDynamicVirtuals(this.model.base, results, dynamicVirtuals, populate, undefined, this.model) as T[];\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 const truncated = finalResult.length === this.defaultLimit && !options.limit;\n\n if (truncated) {\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)), truncated };\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 => toPlainObject(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;;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,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,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"}
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 { isObject } from '#util/common/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_MAX_TIME_MS, MONGO_SLUG_MAX_ATTEMPTS } from './mongo.constant.js';\nimport { wrapNotFound } from './mongo.controller.helpers.js';\nimport { filterDynamicVirtualsFromPopulate, populateDynamicVirtuals } from './mongo.dynamic-populate.js';\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 private defaultProjection: T_ProjectionType<T>;\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: 1,000).\n * @param options.defaultProjection - Default projection to apply to findOne and findAll queries.\n */\n constructor(private model: I_ExtendedModel<T>, options?: { defaultLimit?: number; defaultProjection?: T_ProjectionType<T> }) {\n this.defaultLimit = options?.defaultLimit ?? 1_000;\n this.defaultProjection = options?.defaultProjection ?? {};\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 populated = await this.populateDynamic([result], populate);\n return populated[0] ?? 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 return this.populateDynamic(results, populate);\n }\n\n /**\n * Internal helper that populates dynamic virtuals for an array of documents.\n * Shared implementation used by both single-document and multi-document methods.\n */\n private async populateDynamic(results: T[], populate?: T_Input_Populate): Promise<T[]> {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0 && results.length > 0) {\n return await populateDynamicVirtuals(this.model.base, results, dynamicVirtuals, populate, undefined, this.model) as T[];\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 appliedProjection = Object.keys(projection).length > 0 ? projection : Object.keys(this.defaultProjection).length > 0 ? this.defaultProjection : projection;\n const query = this.model.findOne(normalizedFilter, appliedProjection, options).maxTimeMS(MONGO_MAX_TIME_MS).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 wrapNotFound(this.getModelName());\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 appliedProjection = Object.keys(projection).length > 0 ? projection : Object.keys(this.defaultProjection).length > 0 ? this.defaultProjection : projection;\n const query = this.model.find(normalizedFilter, appliedProjection, options).maxTimeMS(MONGO_MAX_TIME_MS).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 const truncated = finalResult.length === this.defaultLimit && !options.limit;\n\n if (truncated) {\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)), truncated };\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 => toPlainObject(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 wrapNotFound(this.getModelName());\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 wrapNotFound(this.getModelName());\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 wrapNotFound('documents');\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":";;;;;;;;;AAoBA,SAAS,EAAiB,GAAW;AACjC,QAAQ,GAAoC,YAAY,IAAI;;AAchE,IAAa,IAAb,MAA+D;CAC3D;CACA;CAUA,YAAY,GAAmC,GAA8E;AAEzH,EAFgB,KAAA,QAAA,GAChB,KAAK,eAAe,GAAS,gBAAgB,KAC7C,KAAK,oBAAoB,GAAS,qBAAqB,EAAE;;CAQ7D,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;AAEjG,UADkB,MAAM,KAAK,gBAAgB,CAAC,EAAO,EAAE,EAAS,EAC/C,MAAM;;CAU3B,MAAc,oCAA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AAM,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"}
@@ -1,5 +1,5 @@
1
- import { I_Return } from '../../../typescript/index.js';
2
- import { C_Db, C_Document, T_DeleteResult, T_Filter, T_UpdateResult, T_WithId } from './mongo.type.js';
1
+ import { I_Return } from '../../typescript/index.js';
2
+ import { C_Db, C_Document, T_BulkWriteOperation, T_BulkWriteResult, T_DeleteResult, T_Filter, T_UpdateResult, T_WithId } from './mongo.type.js';
3
3
  /**
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,
@@ -51,7 +51,10 @@ export declare class MongoController<D extends Partial<C_Document>> {
51
51
  * @param filter - The filter criteria to find documents (defaults to empty object for all documents).
52
52
  * @returns A promise that resolves to a standardized response with the found documents.
53
53
  */
54
- findAll(filter?: T_Filter<D>): Promise<I_Return<T_WithId<D>[]>>;
54
+ findAll(filter?: T_Filter<D>, options?: {
55
+ skip?: number;
56
+ limit?: number;
57
+ }): Promise<I_Return<T_WithId<D>[]>>;
55
58
  /**
56
59
  * Counts documents matching the filter criteria.
57
60
  *
@@ -89,4 +92,28 @@ export declare class MongoController<D extends Partial<C_Document>> {
89
92
  * @returns A promise that resolves to a standardized response with the delete result.
90
93
  */
91
94
  deleteMany(filter: T_Filter<D>): Promise<I_Return<T_DeleteResult>>;
95
+ /**
96
+ * Executes multiple write operations in a single batch.
97
+ * Use this for high-performance ingestion or batched updates.
98
+ * Note: This method does NOT automatically add generic fields (id, timestamps)
99
+ * to the documents. If required, inject these fields before invoking bulkWrite.
100
+ *
101
+ * @param operations - The array of bulk write operations.
102
+ * @returns A promise that resolves to a standardized response with the bulk write result.
103
+ */
104
+ bulkWrite(operations: T_BulkWriteOperation<D>[]): Promise<I_Return<T_BulkWriteResult>>;
92
105
  }
106
+ /**
107
+ * Factory function to create a native MongoController.
108
+ * Use this method to construct controllers in migration scripts or services.
109
+ *
110
+ * @param db - The MongoDB database instance.
111
+ * @param collectionName - The name of the collection.
112
+ * @param options - Controller options.
113
+ * @param options.defaultLimit - Optional default limit for pagination.
114
+ * @returns A new MongoController instance for the given collection.
115
+ * @since 3.13.0
116
+ */
117
+ export declare function createMongoController<D extends Partial<C_Document>>(db: C_Db, collectionName: string, options?: {
118
+ defaultLimit?: number;
119
+ }): MongoController<D>;
@@ -1,8 +1,9 @@
1
1
  import { catchError as e, log as t } from "../log/log.util.js";
2
- import { mongo as n } from "./mongo.util.js";
2
+ import { MONGO_MAX_TIME_MS as n } from "./mongo.constant.js";
3
3
  import { wrapError as r, wrapNotFound as i } from "./mongo.controller.helpers.js";
4
+ import { mongo as a } from "./mongo.util.js";
4
5
  //#region src/node/mongo/mongo.controller.native.ts
5
- var a = class {
6
+ var o = class {
6
7
  collection;
7
8
  defaultLimit;
8
9
  collectionName;
@@ -12,7 +13,7 @@ var a = class {
12
13
  async createOne(t) {
13
14
  try {
14
15
  let e = {
15
- ...n.createGenericFields(),
16
+ ...a.createGenericFields(),
16
17
  ...t
17
18
  };
18
19
  return (await this.collection.insertOne(e)).acknowledged ? {
@@ -27,12 +28,12 @@ var a = class {
27
28
  async createMany(t) {
28
29
  try {
29
30
  let e = t.map((e) => ({
30
- ...n.createGenericFields(),
31
+ ...a.createGenericFields(),
31
32
  ...e
32
- })), i = await this.collection.insertMany(e);
33
- return i.insertedCount === 0 ? r("No documents were inserted") : {
33
+ })), n = await this.collection.insertMany(e);
34
+ return n.insertedCount === 0 ? r("No documents were inserted") : {
34
35
  success: !0,
35
- message: `${i.insertedCount} documents created successfully`,
36
+ message: `${n.insertedCount} documents created successfully`,
36
37
  result: e
37
38
  };
38
39
  } catch (t) {
@@ -41,7 +42,7 @@ var a = class {
41
42
  }
42
43
  async findOne(t) {
43
44
  try {
44
- let e = await this.collection.findOne(t, { maxTimeMS: 3e4 });
45
+ let e = await this.collection.findOne(t, { maxTimeMS: n });
45
46
  return e ? {
46
47
  success: !0,
47
48
  message: "Document found",
@@ -51,14 +52,16 @@ var a = class {
51
52
  return e(t);
52
53
  }
53
54
  }
54
- async findAll(n = {}) {
55
+ async findAll(r = {}, i) {
55
56
  try {
56
- let e = await this.collection.find(n).limit(this.defaultLimit).maxTimeMS(3e4).toArray(), r = e.length === this.defaultLimit;
57
- return r && t.warn(`[${this.collectionName}] findAll returned exactly ${this.defaultLimit} documents (the default limit). Results may be truncated. Consider using pagination or setting an explicit limit.`), {
57
+ let e = i?.limit ?? this.defaultLimit, a = this.collection.find(r).limit(e).maxTimeMS(n);
58
+ i?.skip && (a = a.skip(i.skip));
59
+ let o = await a.toArray(), s = o.length === e;
60
+ return s && t.warn(`[${this.collectionName}] findAll returned exactly ${e} documents (the limit). Results may be truncated. Consider using pagination or setting an explicit limit.`), {
58
61
  success: !0,
59
62
  message: "Documents retrieved successfully",
60
- result: e,
61
- truncated: r
63
+ result: o,
64
+ truncated: s
62
65
  };
63
66
  } catch (t) {
64
67
  return e(t);
@@ -124,8 +127,22 @@ var a = class {
124
127
  return e(t);
125
128
  }
126
129
  }
130
+ async bulkWrite(t) {
131
+ try {
132
+ return t.length ? {
133
+ success: !0,
134
+ message: "Bulk write executed successfully",
135
+ result: await this.collection.bulkWrite(t)
136
+ } : r("No bulk write operations provided");
137
+ } catch (t) {
138
+ return e(t);
139
+ }
140
+ }
127
141
  };
142
+ function s(e, t, n) {
143
+ return new o(e, t, n);
144
+ }
128
145
  //#endregion
129
- export { a as MongoController };
146
+ export { o as MongoController, s as createMongoController };
130
147
 
131
148
  //# sourceMappingURL=mongo.controller.native.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mongo.controller.native.js","names":[],"sources":["../../../src/node/mongo/mongo.controller.native.ts"],"sourcesContent":["import type { I_Return } from '#typescript/index.js';\n\nimport type { C_Collection, C_Db, C_Document, T_DeleteResult, T_Filter, T_OptionalUnlessRequiredId, T_UpdateResult, T_WithId } from './mongo.type.js';\n\nimport { catchError, log } from '../log/index.js';\nimport { wrapError, wrapNotFound } from './mongo.controller.helpers.js';\nimport { mongo } from './mongo.util.js';\n\n/**\n * MongoDB native driver controller for direct database operations.\n * This class provides a simplified interface for MongoDB operations using the native driver,\n * with automatic generic field generation and standardized response formatting.\n *\n * @see I_MongoController for the shared polymorphic interface (use via type assertion when needed).\n */\nexport class MongoController<D extends Partial<C_Document>> {\n private collection: C_Collection<D>;\n private defaultLimit: number;\n private collectionName: string;\n\n /**\n * Creates a new MongoDB controller instance.\n *\n * @param db - The MongoDB database instance.\n * @param collectionName - The name of the collection 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: 1,000).\n */\n constructor(db: C_Db, collectionName: string, options?: { defaultLimit?: number }) {\n this.collection = db.collection<D>(collectionName);\n this.collectionName = collectionName;\n this.defaultLimit = options?.defaultLimit ?? 1_000;\n }\n\n /**\n * Creates a single document in the collection.\n * This method adds generic fields (id, isDel, timestamps) to the document before insertion.\n *\n * @param document - The document to create, with or without generic fields.\n * @returns A promise that resolves to a standardized response with the created document.\n */\n async createOne(document: D | Partial<D>): Promise<I_Return<D | Partial<D>>> {\n try {\n const finalDocument = {\n ...mongo.createGenericFields(),\n ...document,\n };\n\n const result = await this.collection.insertOne(finalDocument as unknown as T_OptionalUnlessRequiredId<D>);\n\n if (!result.acknowledged) {\n return wrapError('Document creation failed');\n }\n\n return {\n success: true,\n message: 'Document created successfully',\n result: finalDocument,\n };\n }\n catch (error) {\n return catchError<(D | Partial<D>)>(error);\n }\n }\n\n /**\n * Creates multiple documents in the collection.\n * This method adds generic fields to each document before bulk insertion.\n *\n * @param documents - An array of documents to create.\n * @returns A promise that resolves to a standardized response with the created documents.\n */\n async createMany(documents: (D | Partial<D>)[]): Promise<I_Return<(D | Partial<D>)[]>> {\n try {\n const finalDocuments = documents.map(document => ({\n ...mongo.createGenericFields(),\n ...document,\n }));\n\n const result = await this.collection.insertMany(finalDocuments as unknown as T_OptionalUnlessRequiredId<D>[]);\n\n if (result.insertedCount === 0) {\n return wrapError('No documents were inserted');\n }\n\n return {\n success: true,\n message: `${result.insertedCount} documents created successfully`,\n result: finalDocuments,\n };\n }\n catch (error) {\n return catchError<(D | Partial<D>)[]>(error);\n }\n }\n\n /**\n * Finds a single document by filter criteria.\n *\n * @param filter - The filter criteria to find the document.\n * @returns A promise that resolves to a standardized response with the found document.\n */\n async findOne(filter: T_Filter<D>): Promise<I_Return<T_WithId<D>>> {\n try {\n const result = await this.collection.findOne(filter, { maxTimeMS: 30_000 });\n\n if (!result) {\n return wrapNotFound('Document');\n }\n\n return { success: true, message: 'Document found', result };\n }\n catch (error) {\n return catchError<T_WithId<D>>(error);\n }\n }\n\n /**\n * Finds all documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents (defaults to empty object for all documents).\n * @returns A promise that resolves to a standardized response with the found documents.\n */\n async findAll(\n filter: T_Filter<D> = {},\n ): Promise<I_Return<T_WithId<D>[]>> {\n try {\n const result = await this.collection.find(filter).limit(this.defaultLimit).maxTimeMS(30_000).toArray();\n\n const truncated = result.length === this.defaultLimit;\n\n if (truncated) {\n log.warn(`[${this.collectionName}] 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 {\n success: true,\n message: 'Documents retrieved successfully',\n result,\n truncated,\n };\n }\n catch (error) {\n return catchError<T_WithId<D>[]>(error);\n }\n }\n\n /**\n * Counts documents matching the filter criteria.\n *\n * @param filter - The filter criteria to count documents (defaults to empty object for all documents).\n * @returns A promise that resolves to a standardized response with the document count.\n */\n async count(\n filter: T_Filter<D> = {},\n ): Promise<I_Return<number>> {\n try {\n const result = await this.collection.countDocuments(filter);\n\n return {\n success: true,\n message: `${result} documents counted successfully`,\n result,\n };\n }\n catch (error) {\n return catchError<number>(error);\n }\n }\n\n /**\n * Updates a single document matching the filter criteria.\n *\n * @param filter - The filter criteria to find the document to update.\n * @param update - The update data to apply to the document.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateOne(\n filter: T_Filter<D>,\n update: Partial<D>,\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const result = await this.collection.updateOne(filter, {\n $set: update,\n });\n\n if (result.matchedCount === 0) {\n return wrapNotFound('No documents matched the filter');\n }\n return {\n success: true,\n message: 'Document updated successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_UpdateResult>(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 to the documents.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateMany(\n filter: T_Filter<D>,\n update: Partial<D>,\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const result = await this.collection.updateMany(filter, {\n $set: update,\n });\n\n if (result.matchedCount === 0) {\n return wrapNotFound('No documents matched the filter');\n }\n\n return {\n success: true,\n message: 'Documents updated successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Deletes a single document matching the filter criteria.\n *\n * @param filter - The filter criteria to find the document to delete.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteOne(\n filter: T_Filter<D>,\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const result = await this.collection.deleteOne(filter);\n\n if (result.deletedCount === 0) {\n return wrapNotFound('No documents matched the filter');\n }\n return {\n success: true,\n message: 'Document deleted successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_DeleteResult>(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 * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteMany(\n filter: T_Filter<D>,\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const result = await this.collection.deleteMany(filter);\n\n if (result.deletedCount === 0) {\n return wrapNotFound('No documents matched the filter');\n }\n\n return {\n success: true,\n message: 'Documents deleted successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n}\n"],"mappings":";;;;AAeA,IAAa,IAAb,MAA4D;CACxD;CACA;CACA;CAUA,YAAY,GAAU,GAAwB,GAAqC;AAG/E,EAFA,KAAK,aAAa,EAAG,WAAc,EAAe,EAClD,KAAK,iBAAiB,GACtB,KAAK,eAAe,GAAS,gBAAgB;;CAUjD,MAAM,UAAU,GAA6D;AACzE,MAAI;GACA,IAAM,IAAgB;IAClB,GAAG,EAAM,qBAAqB;IAC9B,GAAG;IACN;AAQD,WANe,MAAM,KAAK,WAAW,UAAU,EAA0D,EAE7F,eAIL;IACH,SAAS;IACT,SAAS;IACT,QAAQ;IACX,GAPU,EAAU,2BAA2B;WAS7C,GAAO;AACV,UAAO,EAA6B,EAAM;;;CAWlD,MAAM,WAAW,GAAsE;AACnF,MAAI;GACA,IAAM,IAAiB,EAAU,KAAI,OAAa;IAC9C,GAAG,EAAM,qBAAqB;IAC9B,GAAG;IACN,EAAE,EAEG,IAAS,MAAM,KAAK,WAAW,WAAW,EAA6D;AAM7G,UAJI,EAAO,kBAAkB,IAClB,EAAU,6BAA6B,GAG3C;IACH,SAAS;IACT,SAAS,GAAG,EAAO,cAAc;IACjC,QAAQ;IACX;WAEE,GAAO;AACV,UAAO,EAA+B,EAAM;;;CAUpD,MAAM,QAAQ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F,GACiC;AACjC,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,UAAU,EAAO;AAKtD,UAHI,EAAO,iBAAiB,IACjB,EAAa,kCAAkC,GAEnD;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM;;;CAUhD,MAAM,WACF,GACiC;AACjC,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,WAAW,EAAO;AAMvD,UAJI,EAAO,iBAAiB,IACjB,EAAa,kCAAkC,GAGnD;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM"}
1
+ {"version":3,"file":"mongo.controller.native.js","names":[],"sources":["../../../src/node/mongo/mongo.controller.native.ts"],"sourcesContent":["import type { I_Return } from '#typescript/index.js';\n\nimport type { C_Collection, C_Db, C_Document, T_BulkWriteOperation, T_BulkWriteResult, T_DeleteResult, T_Filter, T_OptionalUnlessRequiredId, T_UpdateResult, T_WithId } from './mongo.type.js';\n\nimport { catchError, log } from '../log/index.js';\nimport { MONGO_MAX_TIME_MS } from './mongo.constant.js';\nimport { wrapError, wrapNotFound } from './mongo.controller.helpers.js';\nimport { mongo } from './mongo.util.js';\n\n/**\n * MongoDB native driver controller for direct database operations.\n * This class provides a simplified interface for MongoDB operations using the native driver,\n * with automatic generic field generation and standardized response formatting.\n *\n * @see I_MongoController for the shared polymorphic interface (use via type assertion when needed).\n */\nexport class MongoController<D extends Partial<C_Document>> {\n private collection: C_Collection<D>;\n private defaultLimit: number;\n private collectionName: string;\n\n /**\n * Creates a new MongoDB controller instance.\n *\n * @param db - The MongoDB database instance.\n * @param collectionName - The name of the collection 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: 1,000).\n */\n constructor(db: C_Db, collectionName: string, options?: { defaultLimit?: number }) {\n this.collection = db.collection<D>(collectionName);\n this.collectionName = collectionName;\n this.defaultLimit = options?.defaultLimit ?? 1_000;\n }\n\n /**\n * Creates a single document in the collection.\n * This method adds generic fields (id, isDel, timestamps) to the document before insertion.\n *\n * @param document - The document to create, with or without generic fields.\n * @returns A promise that resolves to a standardized response with the created document.\n */\n async createOne(document: D | Partial<D>): Promise<I_Return<D | Partial<D>>> {\n try {\n const finalDocument = {\n ...mongo.createGenericFields(),\n ...document,\n };\n\n const result = await this.collection.insertOne(finalDocument as unknown as T_OptionalUnlessRequiredId<D>);\n\n if (!result.acknowledged) {\n return wrapError('Document creation failed');\n }\n\n return {\n success: true,\n message: 'Document created successfully',\n result: finalDocument,\n };\n }\n catch (error) {\n return catchError<(D | Partial<D>)>(error);\n }\n }\n\n /**\n * Creates multiple documents in the collection.\n * This method adds generic fields to each document before bulk insertion.\n *\n * @param documents - An array of documents to create.\n * @returns A promise that resolves to a standardized response with the created documents.\n */\n async createMany(documents: (D | Partial<D>)[]): Promise<I_Return<(D | Partial<D>)[]>> {\n try {\n const finalDocuments = documents.map(document => ({\n ...mongo.createGenericFields(),\n ...document,\n }));\n\n const result = await this.collection.insertMany(finalDocuments as unknown as T_OptionalUnlessRequiredId<D>[]);\n\n if (result.insertedCount === 0) {\n return wrapError('No documents were inserted');\n }\n\n return {\n success: true,\n message: `${result.insertedCount} documents created successfully`,\n result: finalDocuments,\n };\n }\n catch (error) {\n return catchError<(D | Partial<D>)[]>(error);\n }\n }\n\n /**\n * Finds a single document by filter criteria.\n *\n * @param filter - The filter criteria to find the document.\n * @returns A promise that resolves to a standardized response with the found document.\n */\n async findOne(filter: T_Filter<D>): Promise<I_Return<T_WithId<D>>> {\n try {\n const result = await this.collection.findOne(filter, { maxTimeMS: MONGO_MAX_TIME_MS });\n\n if (!result) {\n return wrapNotFound('Document');\n }\n\n return { success: true, message: 'Document found', result };\n }\n catch (error) {\n return catchError<T_WithId<D>>(error);\n }\n }\n\n /**\n * Finds all documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents (defaults to empty object for all documents).\n * @returns A promise that resolves to a standardized response with the found documents.\n */\n async findAll(\n filter: T_Filter<D> = {},\n options?: { skip?: number; limit?: number },\n ): Promise<I_Return<T_WithId<D>[]>> {\n try {\n const limit = options?.limit ?? this.defaultLimit;\n let query = this.collection.find(filter).limit(limit).maxTimeMS(MONGO_MAX_TIME_MS);\n\n if (options?.skip) {\n query = query.skip(options.skip);\n }\n\n const result = await query.toArray();\n\n const truncated = result.length === limit;\n\n if (truncated) {\n log.warn(`[${this.collectionName}] findAll returned exactly ${limit} documents (the limit). Results may be truncated. Consider using pagination or setting an explicit limit.`);\n }\n\n return {\n success: true,\n message: 'Documents retrieved successfully',\n result,\n truncated,\n };\n }\n catch (error) {\n return catchError<T_WithId<D>[]>(error);\n }\n }\n\n /**\n * Counts documents matching the filter criteria.\n *\n * @param filter - The filter criteria to count documents (defaults to empty object for all documents).\n * @returns A promise that resolves to a standardized response with the document count.\n */\n async count(\n filter: T_Filter<D> = {},\n ): Promise<I_Return<number>> {\n try {\n const result = await this.collection.countDocuments(filter);\n\n return {\n success: true,\n message: `${result} documents counted successfully`,\n result,\n };\n }\n catch (error) {\n return catchError<number>(error);\n }\n }\n\n /**\n * Updates a single document matching the filter criteria.\n *\n * @param filter - The filter criteria to find the document to update.\n * @param update - The update data to apply to the document.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateOne(\n filter: T_Filter<D>,\n update: Partial<D>,\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const result = await this.collection.updateOne(filter, {\n $set: update,\n });\n\n if (result.matchedCount === 0) {\n return wrapNotFound('No documents matched the filter');\n }\n return {\n success: true,\n message: 'Document updated successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_UpdateResult>(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 to the documents.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateMany(\n filter: T_Filter<D>,\n update: Partial<D>,\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const result = await this.collection.updateMany(filter, {\n $set: update,\n });\n\n if (result.matchedCount === 0) {\n return wrapNotFound('No documents matched the filter');\n }\n\n return {\n success: true,\n message: 'Documents updated successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Deletes a single document matching the filter criteria.\n *\n * @param filter - The filter criteria to find the document to delete.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteOne(\n filter: T_Filter<D>,\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const result = await this.collection.deleteOne(filter);\n\n if (result.deletedCount === 0) {\n return wrapNotFound('No documents matched the filter');\n }\n return {\n success: true,\n message: 'Document deleted successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_DeleteResult>(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 * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteMany(\n filter: T_Filter<D>,\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const result = await this.collection.deleteMany(filter);\n\n if (result.deletedCount === 0) {\n return wrapNotFound('No documents matched the filter');\n }\n\n return {\n success: true,\n message: 'Documents deleted successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n\n /**\n * Executes multiple write operations in a single batch.\n * Use this for high-performance ingestion or batched updates.\n * Note: This method does NOT automatically add generic fields (id, timestamps)\n * to the documents. If required, inject these fields before invoking bulkWrite.\n *\n * @param operations - The array of bulk write operations.\n * @returns A promise that resolves to a standardized response with the bulk write result.\n */\n async bulkWrite(\n operations: T_BulkWriteOperation<D>[],\n ): Promise<I_Return<T_BulkWriteResult>> {\n try {\n if (!operations.length) {\n return wrapError('No bulk write operations provided');\n }\n\n const result = await this.collection.bulkWrite(operations);\n\n return {\n success: true,\n message: 'Bulk write executed successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_BulkWriteResult>(error);\n }\n }\n}\n\n/**\n * Factory function to create a native MongoController.\n * Use this method to construct controllers in migration scripts or services.\n *\n * @param db - The MongoDB database instance.\n * @param collectionName - The name of the collection.\n * @param options - Controller options.\n * @param options.defaultLimit - Optional default limit for pagination.\n * @returns A new MongoController instance for the given collection.\n * @since 3.13.0\n */\nexport function createMongoController<D extends Partial<C_Document>>(\n db: C_Db,\n collectionName: string,\n options?: { defaultLimit?: number },\n): MongoController<D> {\n return new MongoController<D>(db, collectionName, options);\n}\n"],"mappings":";;;;;AAgBA,IAAa,IAAb,MAA4D;CACxD;CACA;CACA;CAUA,YAAY,GAAU,GAAwB,GAAqC;AAG/E,EAFA,KAAK,aAAa,EAAG,WAAc,EAAe,EAClD,KAAK,iBAAiB,GACtB,KAAK,eAAe,GAAS,gBAAgB;;CAUjD,MAAM,UAAU,GAA6D;AACzE,MAAI;GACA,IAAM,IAAgB;IAClB,GAAG,EAAM,qBAAqB;IAC9B,GAAG;IACN;AAQD,WANe,MAAM,KAAK,WAAW,UAAU,EAA0D,EAE7F,eAIL;IACH,SAAS;IACT,SAAS;IACT,QAAQ;IACX,GAPU,EAAU,2BAA2B;WAS7C,GAAO;AACV,UAAO,EAA6B,EAAM;;;CAWlD,MAAM,WAAW,GAAsE;AACnF,MAAI;GACA,IAAM,IAAiB,EAAU,KAAI,OAAa;IAC9C,GAAG,EAAM,qBAAqB;IAC9B,GAAG;IACN,EAAE,EAEG,IAAS,MAAM,KAAK,WAAW,WAAW,EAA6D;AAM7G,UAJI,EAAO,kBAAkB,IAClB,EAAU,6BAA6B,GAG3C;IACH,SAAS;IACT,SAAS,GAAG,EAAO,cAAc;IACjC,QAAQ;IACX;WAEE,GAAO;AACV,UAAO,EAA+B,EAAM;;;CAUpD,MAAM,QAAQ,GAAqD;AAC/D,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,QAAQ,GAAQ,EAAE,WAAW,GAAmB,CAAC;AAMtF,UAJK,IAIE;IAAE,SAAS;IAAM,SAAS;IAAkB;IAAQ,GAHhD,EAAa,WAAW;WAK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EAAO,iBAAiB,IACjB,EAAa,kCAAkC,GAEnD;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM;;;CAUhD,MAAM,WACF,GACiC;AACjC,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,WAAW,EAAO;AAMvD,UAJI,EAAO,iBAAiB,IACjB,EAAa,kCAAkC,GAGnD;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM;;;CAahD,MAAM,UACF,GACoC;AACpC,MAAI;AAOA,UANK,EAAW,SAMT;IACH,SAAS;IACT,SAAS;IACT,QALW,MAAM,KAAK,WAAW,UAAU,EAAW;IAMzD,GATU,EAAU,oCAAoC;WAWtD,GAAO;AACV,UAAO,EAA8B,EAAM;;;;AAgBvD,SAAgB,EACZ,GACA,GACA,GACkB;AAClB,QAAO,IAAI,EAAmB,GAAI,GAAgB,EAAQ"}
@@ -1,4 +1,4 @@
1
- import { I_Return } from '../../../typescript/index.js';
1
+ import { I_Return } from '../../typescript/index.js';
2
2
  import { T_DeleteResult, T_UpdateResult, T_WithId } from './mongo.type.js';
3
3
  /**
4
4
  * Shared controller interface for MongoDB operations.
@@ -1,4 +1,4 @@
1
- import { DeleteResult, Filter, InsertManyResult, InsertOneResult, OptionalUnlessRequiredId, UpdateResult, WithId, Collection, Db } from 'mongodb';
1
+ import { AnyBulkWriteOperation, BulkWriteResult, DeleteResult, Filter, InsertManyResult, InsertOneResult, OptionalUnlessRequiredId, UpdateResult, WithId, Collection, Db } from 'mongodb';
2
2
  import { AggregatePaginateModel, AggregatePaginateResult, ClientSession, ErrorHandlingMiddlewareFunction, ErrorHandlingMiddlewareWithOption, InsertManyOptions, PaginateModel, PaginateOptions, PaginateResult, PipelineStage, PopulateOption, PopulateOptions, PostMiddlewareFunction, PreMiddlewareFunction, PreSaveMiddlewareFunction, ProjectionType, QueryFilter, QueryOptions, QueryWithHelpers, Schema, SchemaDefinition, UpdateQuery, UpdateWriteOpResult, default as mongoose, Document, Model } from 'mongoose';
3
3
  export declare class C_Db extends Db {
4
4
  }
@@ -7,6 +7,8 @@ export type T_InsertOneResult<T> = InsertOneResult<T>;
7
7
  export type T_InsertManyResult<T> = InsertManyResult<T>;
8
8
  export type T_UpdateResult = UpdateResult | UpdateWriteOpResult;
9
9
  export type T_DeleteResult = DeleteResult;
10
+ export type T_BulkWriteOperation<T extends import('mongodb').Document = import('mongodb').Document> = AnyBulkWriteOperation<T>;
11
+ export type T_BulkWriteResult = BulkWriteResult;
10
12
  export type T_WithId<T> = WithId<T>;
11
13
  export type T_OptionalUnlessRequiredId<T> = OptionalUnlessRequiredId<T>;
12
14
  export declare class C_Document extends Document {
@@ -42,6 +42,7 @@ interface I_MongoUtils {
42
42
  isDynamicVirtual: <T, R extends string>(options?: T_VirtualOptions<T, R>) => options is I_DynamicVirtualOptions<T, R>;
43
43
  getNewRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?: T_Filter<T>) => Promise<T[]>;
44
44
  getExistingRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?: T_Filter<T>) => Promise<T_WithId<T>[]>;
45
+ health: (mongooseInstance: typeof mongooseRaw) => Record<string, unknown>;
45
46
  }
46
47
  /**
47
48
  * MongoDB utility object providing comprehensive database operations and utilities.
@@ -4,9 +4,9 @@ import { validate as r } from "../../util/validate/validate.util.js";
4
4
  import { addGitIgnoreEntry as i, writeFileSync as a } from "../fs/fs.util.js";
5
5
  import { MIGRATE_MONGO_CONFIG as o, PATH as s } from "../path/path.constant.js";
6
6
  import "./mongo.populate.js";
7
- import c from "mongoose-aggregate-paginate-v2";
8
- import l from "mongoose-paginate-v2";
9
- import { randomUUID as u } from "node:crypto";
7
+ import { randomUUID as c } from "node:crypto";
8
+ import l from "mongoose-aggregate-paginate-v2";
9
+ import u from "mongoose-paginate-v2";
10
10
  //#region src/node/mongo/mongo.util.ts
11
11
  function d(e) {
12
12
  return e === e.toUpperCase() ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : e;
@@ -14,7 +14,7 @@ function d(e) {
14
14
  var f = {
15
15
  createGenericFields() {
16
16
  return {
17
- id: u(),
17
+ id: c(),
18
18
  isDel: !1,
19
19
  createdAt: /* @__PURE__ */ new Date(),
20
20
  updatedAt: /* @__PURE__ */ new Date()
@@ -32,7 +32,7 @@ var f = {
32
32
  return new e.Schema({
33
33
  id: {
34
34
  type: String,
35
- default: () => u(),
35
+ default: () => c(),
36
36
  unique: !0
37
37
  },
38
38
  isDel: {
@@ -69,9 +69,9 @@ var f = {
69
69
  schema: n,
70
70
  virtuals: r
71
71
  });
72
- (i || a) && f.applyPlugins(s, [i && l, a && c]), f.applyMiddlewares(s, o);
73
- let u = e.model(t, s);
74
- return r.length > 0 && (u._virtualConfigs = r), u;
72
+ (i || a) && f.applyPlugins(s, [i && u, a && l]), f.applyMiddlewares(s, o);
73
+ let c = e.model(t, s);
74
+ return r.length > 0 && (c._virtualConfigs = r), c;
75
75
  },
76
76
  validator: {
77
77
  isRequired() {
@@ -82,7 +82,7 @@ var f = {
82
82
  isUnique(e) {
83
83
  return async function(t) {
84
84
  if (!Array.isArray(e) || e.length === 0) throw Error("Fields must be a non-empty array of strings.");
85
- let n = { $or: e.map((e) => ({ [e]: t })) };
85
+ let n = { $or: e.map((e) => ({ [e]: { $eq: t } })) };
86
86
  return !await this.constructor.exists(n);
87
87
  };
88
88
  },
@@ -122,16 +122,37 @@ var f = {
122
122
  return !!(e && typeof e.ref == "function");
123
123
  },
124
124
  async getNewRecords(e, t, n, r = {}) {
125
- let i = await e.findAll(r);
126
- if (!i.success) throw Error(`Failed to query existing records: ${i.message}`);
127
- if ("truncated" in i && i.truncated) throw Error("getNewRecords: Results were truncated by the default limit. Use pagination or set an explicit limit to ensure complete data.");
128
- return t.filter((e) => !i.result.some((t) => n(t, e)));
125
+ let i = 1e3, a = 0, o = !1, s = [];
126
+ for (; !o;) {
127
+ let t = await e.findAll(r, {
128
+ skip: a,
129
+ limit: i
130
+ });
131
+ if (!t.success) throw Error(`Failed to query existing records on skip ${a}: ${t.message}`);
132
+ s.push(...t.result), t.truncated && t.result.length === i ? a += i : o = !0;
133
+ }
134
+ return t.filter((e) => !s.some((t) => n(t, e)));
129
135
  },
130
136
  async getExistingRecords(e, t, n, r = {}) {
131
- let i = await e.findAll(r);
132
- if (!i.success) throw Error(`Failed to query existing records: ${i.message}`);
133
- if ("truncated" in i && i.truncated) throw Error("getExistingRecords: Results were truncated by the default limit. Use pagination or set an explicit limit to ensure complete data.");
134
- return i.result.filter((e) => t.some((t) => n(e, t)));
137
+ let i = 1e3, a = 0, o = !1, s = [];
138
+ for (; !o;) {
139
+ let t = await e.findAll(r, {
140
+ skip: a,
141
+ limit: i
142
+ });
143
+ if (!t.success) throw Error(`Failed to query existing records on skip ${a}: ${t.message}`);
144
+ s.push(...t.result), t.truncated && t.result.length === i ? a += i : o = !0;
145
+ }
146
+ return s.filter((e) => t.some((t) => n(e, t)));
147
+ },
148
+ health(e) {
149
+ let t = e.connection;
150
+ return {
151
+ readyState: t.readyState,
152
+ host: t.host,
153
+ name: t.name,
154
+ models: Object.keys(e.models).length
155
+ };
135
156
  }
136
157
  };
137
158
  //#endregion