@common-stack/store-mongo 7.1.1-alpha.9 → 7.2.1-alpha.3

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 (31) hide show
  1. package/lib/dataloaders/bulk-dataloader-v2.js.map +1 -1
  2. package/lib/dataloaders/bulk-dataloader.d.ts +1 -1
  3. package/lib/dataloaders/bulk-dataloader.js.map +1 -1
  4. package/lib/index.d.ts +1 -0
  5. package/lib/interfaces/getAllArgs.d.ts +4 -2
  6. package/lib/interfaces/getAllArgs.js +1 -1
  7. package/lib/interfaces/getAllArgs.js.map +1 -1
  8. package/lib/interfaces/index.d.ts +0 -3
  9. package/lib/interfaces/index.old.d.ts +3 -0
  10. package/lib/mixins/BaseServiceMixin.js +13 -0
  11. package/lib/mixins/BaseServiceMixin.js.map +1 -1
  12. package/lib/mixins/__tests__/BaseServiceMixin.test.d.ts +1 -0
  13. package/lib/module.d.ts +1 -1
  14. package/lib/services/BaseService.d.ts +1 -1
  15. package/lib/services/BaseService.js.map +1 -1
  16. package/lib/services/base-proxy-service.d.ts +2 -1
  17. package/lib/services/base-proxy-service.js.map +1 -1
  18. package/lib/services/base-service.d.ts +2 -1
  19. package/lib/services/base-service.js.map +1 -1
  20. package/lib/store/repositories/BaseMongoRepository.d.ts +8 -1
  21. package/lib/store/repositories/BaseMongoRepository.js +42 -8
  22. package/lib/store/repositories/BaseMongoRepository.js.map +1 -1
  23. package/lib/store/repositories/base-repository.d.ts +2 -1
  24. package/lib/store/repositories/base-repository.js.map +1 -1
  25. package/lib/templates/constants/SERVER_TYPES.ts.template +3 -1
  26. package/lib/templates/repositories/IBaseMongoRepository.ts.template +2 -2
  27. package/lib/templates/repositories/IBaseService.ts.template +6 -6
  28. package/lib/templates/repositories/IBaseServiceMixin.ts.template +20 -3
  29. package/lib/templates/repositories/dbCommonTypes.ts.template +2 -1
  30. package/package.json +5 -5
  31. /package/lib/templates/repositories/{IDataloader.ts.template → DataLoader.ts.template} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-dataloader-v2.js","sources":["../../src/dataloaders/bulk-dataloader-v2.ts"],"sourcesContent":["import DataLoader from 'dataloader';\nimport { injectable, unmanaged } from 'inversify';\nimport { FilterQuery } from 'mongoose';\nimport { IBaseService, IDataLoader, AsDomainType } from 'common/server';\n\n@injectable()\nexport class BulkDataLoader2<SchemaType>\n extends DataLoader<string, AsDomainType<SchemaType> | null>\n implements IDataLoader<SchemaType>\n{\n constructor(@unmanaged() private readonly service: IBaseService<SchemaType>) {\n super(async (ids: string[]) => {\n const data = await this.service.getByIds(ids);\n return ids.map((id) => data.find((record) => record.id === id) || null);\n });\n }\n\n withOptions = new DataLoader<DataLoaderOptions<SchemaType>, AsDomainType<SchemaType>[]>(async (options) => {\n const [{ searchKey, comparator, ...rest }] = options;\n const ids = options.map((option) => option.id);\n\n // Create a properly typed criteria object with explicit type assertion\n const criteria = {\n ...(rest.criteria || {}),\n [searchKey as string]: { $in: ids },\n } as FilterQuery<SchemaType>;\n\n const results = await this.service.getAll({\n ...rest,\n criteria,\n });\n\n return options.map((option) =>\n results.filter((item) => {\n if (typeof comparator === 'function') return comparator(option, item);\n return item[searchKey as keyof AsDomainType<SchemaType>]?.toString() === option.id.toString();\n }),\n );\n });\n}\n"],"names":[],"mappings":";AAMO,IAAM,eAAe,GAArB,MAAM,eACT,SAAQ,UAAmD,CAAA;AAGjB,IAAA,OAAA,CAAA;AAA1C,IAAA,WAAA,CAA0C,OAAiC,EAAA;AACvE,QAAA,KAAK,CAAC,OAAO,GAAa,KAAI;YAC1B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9C,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC;AAC5E,SA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AA,eAAe,CAiC3B"}
1
+ {"version":3,"file":"bulk-dataloader-v2.js","sources":["../../src/dataloaders/bulk-dataloader-v2.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\nimport DataLoader from 'dataloader';\nimport { injectable, unmanaged } from 'inversify';\nimport { FilterQuery } from 'mongoose';\nimport { IBaseService, IDataLoader, AsDomainType, DataLoaderOptions } from 'common/server';\n\n@injectable()\nexport class BulkDataLoader2<SchemaType>\n extends DataLoader<string, AsDomainType<SchemaType> | null>\n implements IDataLoader<SchemaType>\n{\n constructor(@unmanaged() private readonly service: IBaseService<SchemaType>) {\n super(async (ids: string[]) => {\n const data = await this.service.getByIds(ids);\n return ids.map((id) => data.find((record) => record.id === id) || null);\n });\n }\n\n withOptions = new DataLoader<DataLoaderOptions<SchemaType>, AsDomainType<SchemaType>[]>(async (options) => {\n const [{ searchKey, comparator, ...rest }] = options;\n const ids = options.map((option) => option.id);\n\n // Create a properly typed criteria object with explicit type assertion\n const criteria = {\n ...(rest.criteria || {}),\n [searchKey as string]: { $in: ids },\n } as FilterQuery<SchemaType>;\n\n const results = await this.service.getAll({\n ...rest,\n criteria,\n });\n\n return options.map((option) =>\n results.filter((item) => {\n if (typeof comparator === 'function') return comparator(option, item);\n return item[searchKey as keyof AsDomainType<SchemaType>]?.toString() === option.id.toString();\n }),\n );\n });\n}\n"],"names":[],"mappings":";AAOO,IAAM,eAAe,GAArB,MAAM,eACT,SAAQ,UAAmD,CAAA;AAGjB,IAAA,OAAA,CAAA;AAA1C,IAAA,WAAA,CAA0C,OAAiC,EAAA;AACvE,QAAA,KAAK,CAAC,OAAO,GAAa,KAAI;YAC1B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9C,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,EAAE,KAAK,EAAE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,GAAA,MAAA,CAAA,CAAA;AAJtD,CAAA,EAAA,eAAe,CAiC3B"}
@@ -1,5 +1,5 @@
1
1
  import DataLoader from 'dataloader';
2
- import { DataLoaderOptions, IBaseService, IDataLoader } from '../interfaces';
2
+ import { DataLoaderOptions, IBaseService, IDataLoader } from '../interfaces/index.old';
3
3
  export declare class BulkDataLoader<T extends {
4
4
  id: string;
5
5
  }> extends DataLoader<string, T | null> implements IDataLoader<T> {
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-dataloader.js","sources":["../../src/dataloaders/bulk-dataloader.ts"],"sourcesContent":["import DataLoader from 'dataloader';\nimport { injectable, unmanaged } from 'inversify';\nimport { DataLoaderOptions, IBaseService, IDataLoader } from '../interfaces';\n\n@injectable()\nexport class BulkDataLoader<T extends { id: string }> extends DataLoader<string, T | null> implements IDataLoader<T> {\n constructor(@unmanaged() private readonly service: IBaseService<T>) {\n super(async (ids: string[]) => {\n const data = await this.service.getByIds(ids);\n return ids.map((id) => data.find((record) => record.id === id) || null);\n });\n }\n\n withOptions = new DataLoader<DataLoaderOptions<T>, T[]>(async (options) => {\n const [{ searchKey, comparator, ...rest }] = options;\n const ids = options.map((option) => option.id);\n const results = await this.service.getAll({\n ...rest,\n criteria: {\n ...rest.criteria,\n [searchKey]: { $in: ids },\n },\n });\n return options.map((option) =>\n results.filter((item) => {\n if (typeof comparator === 'function') return comparator(option, item);\n return item[searchKey].toString() === option.id.toString();\n }),\n );\n });\n}\n"],"names":[],"mappings":"kIAKO,IAAM,cAAc,GAApB,MAAM,cAAyC,SAAQ,UAA4B,CAAA;AAC5C,IAAA,OAAA,CAAA;AAA1C,IAAA,WAAA,CAA0C,OAAwB,EAAA;AAC9D,QAAA,KAAK,CAAC,OAAO,GAAa,KAAI;YAC1B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9C,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,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loader.ts"],"sourcesContent":["import DataLoader from 'dataloader';\nimport { injectable, unmanaged } from 'inversify';\nimport { DataLoaderOptions, IBaseService, IDataLoader } from '../interfaces/index.old';\n\n@injectable()\nexport class BulkDataLoader<T extends { id: string }> extends DataLoader<string, T | null> implements IDataLoader<T> {\n constructor(@unmanaged() private readonly service: IBaseService<T>) {\n super(async (ids: string[]) => {\n const data = await this.service.getByIds(ids);\n return ids.map((id) => data.find((record) => record.id === id) || null);\n });\n }\n\n withOptions = new DataLoader<DataLoaderOptions<T>, T[]>(async (options) => {\n const [{ searchKey, comparator, ...rest }] = options;\n const ids = options.map((option) => option.id);\n const results = await this.service.getAll({\n ...rest,\n criteria: {\n ...rest.criteria,\n [searchKey]: { $in: ids },\n },\n });\n return options.map((option) =>\n results.filter((item) => {\n if (typeof comparator === 'function') return comparator(option, item);\n return item[searchKey].toString() === option.id.toString();\n }),\n );\n });\n}\n"],"names":[],"mappings":"kIAKO,IAAM,cAAc,GAApB,MAAM,cAAyC,SAAQ,UAA4B,CAAA;AAC5C,IAAA,OAAA,CAAA;AAA1C,IAAA,WAAA,CAA0C,OAAwB,EAAA;AAC9D,QAAA,KAAK,CAAC,OAAO,GAAa,KAAI;YAC1B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9C,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC;AAC5E,SAAC,CAAC,CAAC;QAJmC,IAAO,CAAA,OAAA,GAAP,OAAO,CAAiB;KAKjE;IAED,WAAW,GAAG,IAAI,UAAU,CAA4B,OAAO,OAAO,KAAI;AACtE,QAAA,MAAM,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC;AACrD,QAAA,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,EAAE,CAAC,CAAC;QAC/C,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;AACtC,YAAA,GAAG,IAAI;AACP,YAAA,QAAQ,EAAE;gBACN,GAAG,IAAI,CAAC,QAAQ;AAChB,gBAAA,CAAC,SAAS,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE;AAC5B,aAAA;AACJ,SAAA,CAAC,CAAC;AACH,QAAA,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,KACtB,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,KAAI;YACpB,IAAI,OAAO,UAAU,KAAK,UAAU;AAAE,gBAAA,OAAO,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AACtE,YAAA,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,KAAK,MAAM,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC;SAC9D,CAAC,CACL,CAAC;AACN,KAAC,CAAC,CAAC;EACN;AAzBY,cAAc,GAAA,UAAA,CAAA;AAD1B,IAAA,UAAU,EAAE;IAEI,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;;AADf,CAAA,EAAA,cAAc,CAyB1B"}
package/lib/index.d.ts CHANGED
@@ -4,3 +4,4 @@ export * from './store';
4
4
  export * from './dataloaders';
5
5
  export * from './mixins';
6
6
  export * from './interfaces';
7
+ export * from './interfaces/index.old';
@@ -24,11 +24,11 @@
24
24
  * clear contracts for data manipulation throughout the application. They form the foundation
25
25
  * of the data access pattern used across the entire system.
26
26
  *
27
- * @see IBaseRepository2 - Uses these types for repository operations
27
+ * @see IBaseMongoRepository - Uses these types for repository operations
28
28
  * @see IBaseService2 - Implements service methods using these types
29
29
  * @see IDataLoader2 - Utilizes these types for efficient data loading
30
30
  */
31
- import type { FilterQuery } from 'mongoose';
31
+ import type { FilterQuery, ObjectId } from 'mongoose';
32
32
  import type { ISort } from 'common';
33
33
  /**
34
34
  * Interface for the arguments used in the getAll method
@@ -69,6 +69,8 @@ export interface GetAllArgs<T> {
69
69
  * const user: AsDomainType<UserSchema> = { id: '123', name: 'John', email: 'john@example.com' };
70
70
  */
71
71
  export type AsDomainType<SchemaType> = Omit<SchemaType, '_id'> & {
72
+ _id?: ObjectId;
73
+ } & {
72
74
  id: string;
73
75
  };
74
76
  /**
@@ -24,7 +24,7 @@
24
24
  * clear contracts for data manipulation throughout the application. They form the foundation
25
25
  * of the data access pattern used across the entire system.
26
26
  *
27
- * @see IBaseRepository2 - Uses these types for repository operations
27
+ * @see IBaseMongoRepository - Uses these types for repository operations
28
28
  * @see IBaseService2 - Implements service methods using these types
29
29
  * @see IDataLoader2 - Utilizes these types for efficient data loading
30
30
  */
@@ -1 +1 @@
1
- {"version":3,"file":"getAllArgs.js","sources":["../../src/interfaces/getAllArgs.ts"],"sourcesContent":["/**\n * @file get-all-args.ts\n * @description Defines common types and interfaces used across the data access layer for MongoDB operations.\n * This file contains essential type definitions that standardize how data is queried, transformed, and returned.\n *\n * Key components include:\n * - GetAllArgs: Interface for pagination, sorting, and filtering when retrieving collections of documents\n * - AsDomainType: Type transformer that converts MongoDB schema types (with _id) to domain types (with id)\n * - GetAllWithCountResult: Type for paginated results that include both data and total count\n * - CreateType/UpdateType: Utility types that define the shape of data for create and update operations\n * - PAGINATION_OPTIONS: Default pagination settings used throughout the application\n *\n * Usage examples:\n * 1. Retrieving paginated data:\n * const result = await repository.getAllWithCount({ limit: 10, skip: 0, sort: { createdAt: -1 } });\n *\n * 2. Converting MongoDB documents to domain objects:\n * const domainUser: AsDomainType<UserSchema> = { ...userDoc, id: userDoc._id.toString() };\n *\n * 3. Creating new documents with proper typing:\n * const newUser: CreateType<UserSchema> = { name: 'John', email: 'john@example.com' };\n *\n * These types ensure consistency across repositories and services, providing type safety and\n * clear contracts for data manipulation throughout the application. They form the foundation\n * of the data access pattern used across the entire system.\n *\n * @see IBaseRepository2 - Uses these types for repository operations\n * @see IBaseService2 - Implements service methods using these types\n * @see IDataLoader2 - Utilizes these types for efficient data loading\n */\n\nimport type { FilterQuery } from 'mongoose';\nimport type { ISort } from 'common';\n\n/**\n * Interface for the arguments used in the getAll method\n *\n * @property criteria - MongoDB filter query to narrow down results\n * @property sort - Sorting configuration with field names and directions (1 for ascending, -1 for descending)\n * @property skip - Number of documents to skip (for pagination)\n * @property limit - Maximum number of documents to return (for pagination)\n * @property selectedFields - String of space-separated field names to include in the results\n *\n * @example\n * // Get active users, sorted by creation date, second page with 10 items per page\n * const options: GetAllArgs<UserSchema> = {\n * criteria: { active: true },\n * sort: { createdAt: -1 },\n * skip: 10,\n * limit: 10,\n * selectedFields: 'name email createdAt'\n * };\n */\nexport interface GetAllArgs<T> {\n criteria?: FilterQuery<T>;\n sort?: ISort;\n skip?: number;\n limit?: number;\n selectedFields?: string;\n}\n\n/**\n * Type that converts a schema type with _id to a domain type with id\n * This transformation is essential for presenting MongoDB documents as domain objects\n * throughout the application, hiding the database-specific _id field.\n *\n * @example\n * // MongoDB document\n * const userDoc = { _id: '123', name: 'John', email: 'john@example.com' };\n *\n * // Transformed domain object\n * const user: AsDomainType<UserSchema> = { id: '123', name: 'John', email: 'john@example.com' };\n */\nexport type AsDomainType<SchemaType> = Omit<SchemaType, '_id'> & { id: string };\n\n/**\n * Type for the result of getAllWithCount\n * Provides both the paginated data and the total count of matching documents\n * This is used for implementing pagination UI components that need to know\n * the total number of pages or items.\n *\n * @property data - Array of domain objects matching the query criteria\n * @property totalCount - Total number of documents that match the criteria (without pagination)\n *\n * @example\n * const result: GetAllWithCountResult<UserSchema> = {\n * data: [{ id: '1', name: 'John' }, { id: '2', name: 'Jane' }],\n * totalCount: 50\n * };\n */\nexport type GetAllWithCountResult<SchemaType> = {\n data: AsDomainType<SchemaType>[];\n totalCount: number;\n};\n\n/**\n * Default pagination settings used throughout the application\n * These values are used when no explicit pagination parameters are provided\n */\nexport enum PAGINATION_OPTIONS {\n limit = 10,\n skip = 0,\n}\n\n/**\n * Type for create operations - omits _id, id, and auto-generated fields\n * This ensures that clients cannot specify fields that should be generated by the database\n *\n * @example\n * // Valid create operation data\n * const newUser: CreateType<UserSchema> = {\n * name: 'John Doe',\n * email: 'john@example.com',\n * role: 'user'\n * };\n *\n * // The following fields will be generated automatically and should not be included:\n * // - _id (MongoDB document ID)\n * // - id (Domain object ID)\n * // - createdAt (Creation timestamp)\n * // - updatedAt (Last update timestamp)\n */\nexport type CreateType<SchemaType> = Omit<Partial<SchemaType>, '_id' | 'id' | 'createdAt' | 'updatedAt'>;\n\n/**\n * Type for update operations - partial of the schema without _id\n * This allows for partial updates where only changed fields are specified\n *\n * @example\n * // Update a user's email and role\n * const updateData: UpdateType<UserSchema> = {\n * email: 'new.email@example.com',\n * role: 'admin'\n * };\n *\n * // Fields not specified will remain unchanged\n */\nexport type UpdateType<SchemaType> = Partial<Omit<SchemaType, '_id'>>;\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BG;AAkEH;;;AAGG;IACS,mBAGX;AAHD,CAAA,UAAY,kBAAkB,EAAA;AAC1B,IAAA,kBAAA,CAAA,kBAAA,CAAA,OAAA,CAAA,GAAA,EAAA,CAAA,GAAA,OAAU,CAAA;AACV,IAAA,kBAAA,CAAA,kBAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAQ,CAAA;AACZ,CAAC,EAHW,kBAAkB,KAAlB,kBAAkB,GAG7B,EAAA,CAAA,CAAA"}
1
+ {"version":3,"file":"getAllArgs.js","sources":["../../src/interfaces/getAllArgs.ts"],"sourcesContent":["/**\n * @file get-all-args.ts\n * @description Defines common types and interfaces used across the data access layer for MongoDB operations.\n * This file contains essential type definitions that standardize how data is queried, transformed, and returned.\n *\n * Key components include:\n * - GetAllArgs: Interface for pagination, sorting, and filtering when retrieving collections of documents\n * - AsDomainType: Type transformer that converts MongoDB schema types (with _id) to domain types (with id)\n * - GetAllWithCountResult: Type for paginated results that include both data and total count\n * - CreateType/UpdateType: Utility types that define the shape of data for create and update operations\n * - PAGINATION_OPTIONS: Default pagination settings used throughout the application\n *\n * Usage examples:\n * 1. Retrieving paginated data:\n * const result = await repository.getAllWithCount({ limit: 10, skip: 0, sort: { createdAt: -1 } });\n *\n * 2. Converting MongoDB documents to domain objects:\n * const domainUser: AsDomainType<UserSchema> = { ...userDoc, id: userDoc._id.toString() };\n *\n * 3. Creating new documents with proper typing:\n * const newUser: CreateType<UserSchema> = { name: 'John', email: 'john@example.com' };\n *\n * These types ensure consistency across repositories and services, providing type safety and\n * clear contracts for data manipulation throughout the application. They form the foundation\n * of the data access pattern used across the entire system.\n *\n * @see IBaseMongoRepository - Uses these types for repository operations\n * @see IBaseService2 - Implements service methods using these types\n * @see IDataLoader2 - Utilizes these types for efficient data loading\n */\n\nimport type { FilterQuery, ObjectId } from 'mongoose';\nimport type { ISort } from 'common';\n\n/**\n * Interface for the arguments used in the getAll method\n *\n * @property criteria - MongoDB filter query to narrow down results\n * @property sort - Sorting configuration with field names and directions (1 for ascending, -1 for descending)\n * @property skip - Number of documents to skip (for pagination)\n * @property limit - Maximum number of documents to return (for pagination)\n * @property selectedFields - String of space-separated field names to include in the results\n *\n * @example\n * // Get active users, sorted by creation date, second page with 10 items per page\n * const options: GetAllArgs<UserSchema> = {\n * criteria: { active: true },\n * sort: { createdAt: -1 },\n * skip: 10,\n * limit: 10,\n * selectedFields: 'name email createdAt'\n * };\n */\nexport interface GetAllArgs<T> {\n criteria?: FilterQuery<T>;\n sort?: ISort;\n skip?: number;\n limit?: number;\n selectedFields?: string;\n}\n\n/**\n * Type that converts a schema type with _id to a domain type with id\n * This transformation is essential for presenting MongoDB documents as domain objects\n * throughout the application, hiding the database-specific _id field.\n *\n * @example\n * // MongoDB document\n * const userDoc = { _id: '123', name: 'John', email: 'john@example.com' };\n *\n * // Transformed domain object\n * const user: AsDomainType<UserSchema> = { id: '123', name: 'John', email: 'john@example.com' };\n */\nexport type AsDomainType<SchemaType> = Omit<SchemaType, '_id'> & { _id?: ObjectId } & { id: string };\n\n/**\n * Type for the result of getAllWithCount\n * Provides both the paginated data and the total count of matching documents\n * This is used for implementing pagination UI components that need to know\n * the total number of pages or items.\n *\n * @property data - Array of domain objects matching the query criteria\n * @property totalCount - Total number of documents that match the criteria (without pagination)\n *\n * @example\n * const result: GetAllWithCountResult<UserSchema> = {\n * data: [{ id: '1', name: 'John' }, { id: '2', name: 'Jane' }],\n * totalCount: 50\n * };\n */\nexport type GetAllWithCountResult<SchemaType> = {\n data: AsDomainType<SchemaType>[];\n totalCount: number;\n};\n\n/**\n * Default pagination settings used throughout the application\n * These values are used when no explicit pagination parameters are provided\n */\nexport enum PAGINATION_OPTIONS {\n limit = 10,\n skip = 0,\n}\n\n/**\n * Type for create operations - omits _id, id, and auto-generated fields\n * This ensures that clients cannot specify fields that should be generated by the database\n *\n * @example\n * // Valid create operation data\n * const newUser: CreateType<UserSchema> = {\n * name: 'John Doe',\n * email: 'john@example.com',\n * role: 'user'\n * };\n *\n * // The following fields will be generated automatically and should not be included:\n * // - _id (MongoDB document ID)\n * // - id (Domain object ID)\n * // - createdAt (Creation timestamp)\n * // - updatedAt (Last update timestamp)\n */\nexport type CreateType<SchemaType> = Omit<Partial<SchemaType>, '_id' | 'id' | 'createdAt' | 'updatedAt'>;\n\n/**\n * Type for update operations - partial of the schema without _id\n * This allows for partial updates where only changed fields are specified\n *\n * @example\n * // Update a user's email and role\n * const updateData: UpdateType<UserSchema> = {\n * email: 'new.email@example.com',\n * role: 'admin'\n * };\n *\n * // Fields not specified will remain unchanged\n */\nexport type UpdateType<SchemaType> = Partial<Omit<SchemaType, '_id'>>;\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BG;AAkEH;;;AAGG;IACS,mBAGX;AAHD,CAAA,UAAY,kBAAkB,EAAA;AAC1B,IAAA,kBAAA,CAAA,kBAAA,CAAA,OAAA,CAAA,GAAA,EAAA,CAAA,GAAA,OAAU,CAAA;AACV,IAAA,kBAAA,CAAA,kBAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAQ,CAAA;AACZ,CAAC,EAHW,kBAAkB,KAAlB,kBAAkB,GAG7B,EAAA,CAAA,CAAA"}
@@ -1,5 +1,2 @@
1
1
  export * from './mongoose-settings';
2
2
  export * from './getAllArgs';
3
- export * from './base-repository';
4
- export * from './base-service';
5
- export * from './dataloaders';
@@ -0,0 +1,3 @@
1
+ export * from './base-repository';
2
+ export * from './base-service';
3
+ export * from './dataloaders';
@@ -63,6 +63,19 @@ const BaseServiceMixin = (service, broker, name, events = defaultEvents) => ({
63
63
  },
64
64
  handler: async (ctx) => service.get({ id: ctx.params.id }),
65
65
  },
66
+ /**
67
+ * Get multiple documents by their IDs
68
+ */
69
+ [BaseServiceCommands.GetByIds]: {
70
+ params: {
71
+ ids: {
72
+ type: 'array',
73
+ items: 'string',
74
+ optional: false
75
+ },
76
+ },
77
+ handler: async (ctx) => service.getByIds(ctx.params.ids),
78
+ },
66
79
  /**
67
80
  * Count documents matching criteria
68
81
  */
@@ -1 +1 @@
1
- {"version":3,"file":"BaseServiceMixin.js","sources":["../../src/mixins/BaseServiceMixin.ts"],"sourcesContent":["/**\n * @file BaseServiceMixin.ts\n * @description Provides a mixin function that adds standardized service methods to Moleculer service schemas.\n * This mixin implements the IBaseService interface and connects it to Moleculer's service framework,\n * creating action handlers for all standard service operations.\n *\n * The mixin pattern allows for composable service functionality, where multiple mixins can be combined\n * to create feature-rich services without code duplication. This particular mixin handles the core CRUD\n * operations and emits events when data changes.\n *\n * Key features:\n * - Automatic action creation for all IBaseService methods\n * - Event emission for data changes (create, update, delete)\n * - Parameter validation for all actions\n * - Consistent error handling\n * - Type safety through generics\n *\n * @see IBaseService - The interface this mixin implements\n * @see IBaseMongoRepository - The repository interface used for data access\n */\n\n/* eslint-disable import/no-extraneous-dependencies */\nimport { Context, ServiceBroker, ServiceSchema } from 'moleculer';\nimport { Document, FilterQuery } from 'mongoose';\nimport { upperFirst } from 'lodash-es';\nimport { GetAllArgs, IBaseService, BaseServiceCommands } from 'common';\n\n/**\n * Default events that will trigger event emissions when data changes\n * Services can customize this list to control which operations emit events\n */\nconst defaultEvents = [\n BaseServiceCommands.Create,\n BaseServiceCommands.BulkCreate,\n BaseServiceCommands.Update,\n BaseServiceCommands.Delete,\n BaseServiceCommands.DeleteMany,\n];\n\n/**\n * Creates a mixin that implements the IBaseService interface as Moleculer actions\n *\n * @param service - Implementation of IBaseService that will handle the actual business logic\n * @param broker - Moleculer service broker for event emission\n * @param name - Service name used for event naming\n * @param events - List of operations that should emit events\n * @returns A partial ServiceSchema that can be merged with other service definitions\n *\n * @example\n * // Create a user service with the base service mixin\n * const UserService: ServiceSchema = {\n * name: \"users\",\n * mixins: [\n * BaseServiceMixin(userService, broker, \"users\")\n * ],\n * // Additional service-specific actions and methods\n * actions: {\n * changePassword: { ... }\n * }\n * };\n */\nexport const BaseServiceMixin = <T>(\n service: IBaseService<T>,\n broker?: ServiceBroker,\n name?: string,\n events = defaultEvents,\n): Partial<ServiceSchema> => ({\n name: 'BaseServiceMixin',\n actions: {\n /**\n * Get a single document by ID\n */\n [BaseServiceCommands.Get]: {\n params: {\n id: 'string',\n },\n handler: async (ctx: Context<{ id: string }>) =>\n service.get({ id: ctx.params.id } as FilterQuery<Document<T>>),\n },\n\n /**\n * Count documents matching criteria\n */\n [BaseServiceCommands.Count]: {\n params: {\n criteria: { type: 'object', optional: true },\n },\n handler: async (ctx: Context<{ criteria?: FilterQuery<Document<T>> }>) =>\n service.count(ctx.params.criteria),\n },\n\n /**\n * Create multiple documents\n */\n [BaseServiceCommands.BulkCreate]: {\n params: {\n data: { type: 'array', items: 'object' },\n },\n handler: async (ctx: Context<{ data: never[] }>) => {\n const response = await service.bulkCreate(ctx.params.data);\n if (events.includes(BaseServiceCommands.BulkCreate)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.BulkCreate)}`, response);\n }\n return response;\n },\n },\n\n /**\n * Create a single document\n */\n [BaseServiceCommands.Create]: {\n params: {\n data: 'object',\n },\n handler: async (ctx: Context<{ data: never }>) => {\n const response = await service.create(ctx.params.data);\n if (events.includes(BaseServiceCommands.Create)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.Create)}`, response);\n }\n return response;\n },\n },\n\n /**\n * Delete a document by ID\n */\n [BaseServiceCommands.Delete]: {\n params: {\n id: 'string',\n },\n handler: async (ctx: Context<{ id: string }>) => {\n const { id } = ctx.params;\n const response = await service.delete({ id } as FilterQuery<Document<T>>);\n if (events.includes(BaseServiceCommands.Delete)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.Delete)}`, { id });\n }\n return response;\n },\n },\n\n /**\n * Get documents with pagination\n */\n [BaseServiceCommands.GetAll]: {\n params: {\n criteria: 'object|optional',\n sort: 'object|optional',\n skip: 'number|optional',\n limit: 'number|optional',\n selectedFields: 'string|optional',\n },\n handler: async (ctx: Context<GetAllArgs<Document<T>>>) => service.getAll(ctx.params),\n },\n\n /**\n * Get documents with pagination and total count\n */\n [BaseServiceCommands.GetAllWithCount]: {\n params: {\n criteria: 'object|optional',\n sort: 'object|optional',\n skip: 'number|optional',\n limit: 'number|optional',\n selectedFields: 'string|optional',\n },\n handler: async (ctx: Context<GetAllArgs<Document<T>>>) => service.getAllWithCount(ctx.params),\n },\n\n /**\n * Create or update a document\n */\n [BaseServiceCommands.Insert]: {\n params: {\n data: 'object',\n overwrite: 'boolean|optional',\n },\n handler: async (ctx: Context<{ data: never & { id?: string }; overwrite: boolean }>) => {\n const { data } = ctx.params;\n const response = await service.insert(data, ctx.params.overwrite);\n const action = (data as { id: string })?.id ? BaseServiceCommands.Update : BaseServiceCommands.Create;\n if (events.includes(action)) {\n await broker?.emit(`${name}.on${upperFirst(action)}`, response);\n }\n return response;\n },\n },\n\n /**\n * Update a document by ID\n */\n [BaseServiceCommands.Update]: {\n params: {\n id: 'string',\n data: 'object',\n overwrite: 'boolean|optional',\n },\n handler: async (ctx: Context<{ id: string; data: never; overwrite: boolean }>) => {\n const response = await service.update(ctx.params.id, ctx.params.data, ctx.params.overwrite);\n if (events.includes(BaseServiceCommands.Update)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.Update)}`, response);\n }\n return response;\n },\n },\n\n /**\n * Delete multiple documents matching criteria\n */\n [BaseServiceCommands.DeleteMany]: {\n params: {\n criteria: 'object',\n },\n handler: async (ctx: Context<{ criteria: FilterQuery<Document<T>> }>) => {\n const { criteria } = ctx.params;\n const response = await service.delete(criteria);\n if (events.includes(BaseServiceCommands.DeleteMany)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.DeleteMany)}`, criteria);\n }\n return response;\n },\n },\n },\n});\n"],"names":[],"mappings":"4EAAA;;;;;;;;;;;;;;;;;;;AAmBG;AAQH;;;AAGG;AACH,MAAM,aAAa,GAAG;AAClB,IAAA,mBAAmB,CAAC,MAAM;AAC1B,IAAA,mBAAmB,CAAC,UAAU;AAC9B,IAAA,mBAAmB,CAAC,MAAM;AAC1B,IAAA,mBAAmB,CAAC,MAAM;AAC1B,IAAA,mBAAmB,CAAC,UAAU;CACjC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;AAqBG;AACU,MAAA,gBAAgB,GAAG,CAC5B,OAAwB,EACxB,MAAsB,EACtB,IAAa,EACb,MAAM,GAAG,aAAa,MACI;AAC1B,IAAA,IAAI,EAAE,kBAAkB;AACxB,IAAA,OAAO,EAAE;AACL;;AAEG;AACH,QAAA,CAAC,mBAAmB,CAAC,GAAG,GAAG;AACvB,YAAA,MAAM,EAAE;AACJ,gBAAA,EAAE,EAAE,QAAQ;AACf,aAAA;YACD,OAAO,EAAE,OAAO,GAA4B,KACxC,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,EAA8B,CAAC;AACrE,SAAA;AAED;;AAEG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;AACD,YAAA,OAAO,EAAE,OAAO,GAA6D,KAAI;gBAC7E,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;gBAC5F,IAAI,MAAM,CAAC,QAAQ,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE;AAC7C,oBAAA,MAAM,MAAM,EAAE,IAAI,CAAC,CAAA,EAAG,IAAI,CAAM,GAAA,EAAA,UAAU,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;iBACvF;AACD,gBAAA,OAAO,QAAQ,CAAC;aACnB;AACJ,SAAA;AAED;;AAEG;AACH,QAAA,CAAC,mBAAmB,CAAC,UAAU,GAAG;AAC9B,YAAA,MAAM,EAAE;AACJ,gBAAA,QAAQ,EAAE,QAAQ;AACrB,aAAA;AACD,YAAA,OAAO,EAAE,OAAO,GAAoD,KAAI;AACpE,gBAAA,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;gBAChC,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAChD,IAAI,MAAM,CAAC,QAAQ,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE;AACjD,oBAAA,MAAM,MAAM,EAAE,IAAI,CAAC,CAAA,EAAG,IAAI,CAAM,GAAA,EAAA,UAAU,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;iBAC3F;AACD,gBAAA,OAAO,QAAQ,CAAC;aACnB;AACJ,SAAA;AACJ,KAAA;AACJ,CAAA"}
1
+ {"version":3,"file":"BaseServiceMixin.js","sources":["../../src/mixins/BaseServiceMixin.ts"],"sourcesContent":["/**\n * @file BaseServiceMixin.ts\n * @description Provides a mixin function that adds standardized service methods to Moleculer service schemas.\n * This mixin implements the IBaseService interface and connects it to Moleculer's service framework,\n * creating action handlers for all standard service operations.\n *\n * The mixin pattern allows for composable service functionality, where multiple mixins can be combined\n * to create feature-rich services without code duplication. This particular mixin handles the core CRUD\n * operations and emits events when data changes.\n *\n * Key features:\n * - Automatic action creation for all IBaseService methods\n * - Event emission for data changes (create, update, delete)\n * - Parameter validation for all actions\n * - Consistent error handling\n * - Type safety through generics\n *\n * @see IBaseService - The interface this mixin implements\n * @see IBaseMongoRepository - The repository interface used for data access\n */\n\n/* eslint-disable import/no-extraneous-dependencies */\nimport { Context, ServiceBroker, ServiceSchema } from 'moleculer';\nimport { Document, FilterQuery } from 'mongoose';\nimport { upperFirst } from 'lodash-es';\nimport { GetAllArgs, IBaseService, BaseServiceCommands } from 'common';\n\n/**\n * Default events that will trigger event emissions when data changes\n * Services can customize this list to control which operations emit events\n */\nconst defaultEvents = [\n BaseServiceCommands.Create,\n BaseServiceCommands.BulkCreate,\n BaseServiceCommands.Update,\n BaseServiceCommands.Delete,\n BaseServiceCommands.DeleteMany,\n];\n\n/**\n * Creates a mixin that implements the IBaseService interface as Moleculer actions\n *\n * @param service - Implementation of IBaseService that will handle the actual business logic\n * @param broker - Moleculer service broker for event emission\n * @param name - Service name used for event naming\n * @param events - List of operations that should emit events\n * @returns A partial ServiceSchema that can be merged with other service definitions\n *\n * @example\n * // Create a user service with the base service mixin\n * const UserService: ServiceSchema = {\n * name: \"users\",\n * mixins: [\n * BaseServiceMixin(userService, broker, \"users\")\n * ],\n * // Additional service-specific actions and methods\n * actions: {\n * changePassword: { ... }\n * }\n * };\n */\nexport const BaseServiceMixin = <T>(\n service: IBaseService<T>,\n broker?: ServiceBroker,\n name?: string,\n events = defaultEvents,\n): Partial<ServiceSchema> => ({\n name: 'BaseServiceMixin',\n actions: {\n /**\n * Get a single document by ID\n */\n [BaseServiceCommands.Get]: {\n params: {\n id: 'string',\n },\n handler: async (ctx: Context<{ id: string }>) =>\n service.get({ id: ctx.params.id } as FilterQuery<Document<T>>),\n },\n\n /**\n * Get multiple documents by their IDs\n */\n [BaseServiceCommands.GetByIds]: {\n params: {\n ids: { \n type: 'array', \n items: 'string',\n optional: false\n },\n },\n handler: async (ctx: Context<{ ids: string[] }>) => service.getByIds(ctx.params.ids),\n },\n\n /**\n * Count documents matching criteria\n */\n [BaseServiceCommands.Count]: {\n params: {\n criteria: { type: 'object', optional: true },\n },\n handler: async (ctx: Context<{ criteria?: FilterQuery<Document<T>> }>) =>\n service.count(ctx.params.criteria),\n },\n\n /**\n * Create multiple documents\n */\n [BaseServiceCommands.BulkCreate]: {\n params: {\n data: { type: 'array', items: 'object' },\n },\n handler: async (ctx: Context<{ data: never[] }>) => {\n const response = await service.bulkCreate(ctx.params.data);\n if (events.includes(BaseServiceCommands.BulkCreate)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.BulkCreate)}`, response);\n }\n return response;\n },\n },\n\n /**\n * Create a single document\n */\n [BaseServiceCommands.Create]: {\n params: {\n data: 'object',\n },\n handler: async (ctx: Context<{ data: never }>) => {\n const response = await service.create(ctx.params.data);\n if (events.includes(BaseServiceCommands.Create)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.Create)}`, response);\n }\n return response;\n },\n },\n\n /**\n * Delete a document by ID\n */\n [BaseServiceCommands.Delete]: {\n params: {\n id: 'string',\n },\n handler: async (ctx: Context<{ id: string }>) => {\n const { id } = ctx.params;\n const response = await service.delete({ id } as FilterQuery<Document<T>>);\n if (events.includes(BaseServiceCommands.Delete)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.Delete)}`, { id });\n }\n return response;\n },\n },\n\n /**\n * Get documents with pagination\n */\n [BaseServiceCommands.GetAll]: {\n params: {\n criteria: 'object|optional',\n sort: 'object|optional',\n skip: 'number|optional',\n limit: 'number|optional',\n selectedFields: 'string|optional',\n },\n handler: async (ctx: Context<GetAllArgs<Document<T>>>) => service.getAll(ctx.params),\n },\n\n /**\n * Get documents with pagination and total count\n */\n [BaseServiceCommands.GetAllWithCount]: {\n params: {\n criteria: 'object|optional',\n sort: 'object|optional',\n skip: 'number|optional',\n limit: 'number|optional',\n selectedFields: 'string|optional',\n },\n handler: async (ctx: Context<GetAllArgs<Document<T>>>) => service.getAllWithCount(ctx.params),\n },\n\n /**\n * Create or update a document\n */\n [BaseServiceCommands.Insert]: {\n params: {\n data: 'object',\n overwrite: 'boolean|optional',\n },\n handler: async (ctx: Context<{ data: never & { id?: string }; overwrite: boolean }>) => {\n const { data } = ctx.params;\n const response = await service.insert(data, ctx.params.overwrite);\n const action = (data as { id: string })?.id ? BaseServiceCommands.Update : BaseServiceCommands.Create;\n if (events.includes(action)) {\n await broker?.emit(`${name}.on${upperFirst(action)}`, response);\n }\n return response;\n },\n },\n\n /**\n * Update a document by ID\n */\n [BaseServiceCommands.Update]: {\n params: {\n id: 'string',\n data: 'object',\n overwrite: 'boolean|optional',\n },\n handler: async (ctx: Context<{ id: string; data: never; overwrite: boolean }>) => {\n const response = await service.update(ctx.params.id, ctx.params.data, ctx.params.overwrite);\n if (events.includes(BaseServiceCommands.Update)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.Update)}`, response);\n }\n return response;\n },\n },\n\n /**\n * Delete multiple documents matching criteria\n */\n [BaseServiceCommands.DeleteMany]: {\n params: {\n criteria: 'object',\n },\n handler: async (ctx: Context<{ criteria: FilterQuery<Document<T>> }>) => {\n const { criteria } = ctx.params;\n const response = await service.delete(criteria);\n if (events.includes(BaseServiceCommands.DeleteMany)) {\n await broker?.emit(`${name}.on${upperFirst(BaseServiceCommands.DeleteMany)}`, criteria);\n }\n return response;\n },\n },\n },\n});\n"],"names":[],"mappings":"4EAAA;;;;;;;;;;;;;;;;;;;AAmBG;AAQH;;;AAGG;AACH,MAAM,aAAa,GAAG;AAClB,IAAA,mBAAmB,CAAC,MAAM;AAC1B,IAAA,mBAAmB,CAAC,UAAU;AAC9B,IAAA,mBAAmB,CAAC,MAAM;A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AA,EAAA,UAAU,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;iBACvF;AACD,gBAAA,OAAO,QAAQ,CAAC;aACnB;AACJ,SAAA;AAED;;AAEG;AACH,QAAA,CAAC,mBAAmB,CAAC,UAAU,GAAG;AAC9B,YAAA,MAAM,EAAE;AACJ,gBAAA,QAAQ,EAAE,QAAQ;AACrB,aAAA;AACD,YAAA,OAAO,EAAE,OAAO,GAAoD,KAAI;AACpE,gBAAA,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;gBAChC,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAChD,IAAI,MAAM,CAAC,QAAQ,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE;AACjD,oBAAA,MAAM,MAAM,EAAE,IAAI,CAAC,CAAA,EAAG,IAAI,CAAM,GAAA,EAAA,UAAU,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;iBAC3F;AACD,gBAAA,OAAO,QAAQ,CAAC;aACnB;AACJ,SAAA;AACJ,KAAA;AACJ,CAAA"}
@@ -0,0 +1 @@
1
+ export {};
package/lib/module.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { Feature } from '@common-stack/server-core';
2
- declare const _default: Feature<import("@common-stack/server-core").ConfigurationScope, any>;
2
+ declare const _default: Feature<any, any>;
3
3
  export default _default;
@@ -1,6 +1,6 @@
1
1
  import { FilterQuery } from 'mongoose';
2
2
  import { GetAllArgs, IBaseMongoRepository, IBaseService, AsDomainType, CreateType, UpdateType } from 'common/server';
3
- export declare class BaseService2<SchemaType> implements IBaseService<SchemaType> {
3
+ export declare class BaseService2<SchemaType, C = CreateType<SchemaType>, U = UpdateType<SchemaType>> implements IBaseService<SchemaType, C, U> {
4
4
  protected repository: IBaseMongoRepository<SchemaType>;
5
5
  constructor(repository: IBaseMongoRepository<SchemaType>);
6
6
  getAllWithCount(options: GetAllArgs<SchemaType>): Promise<{
@@ -1 +1 @@
1
- {"version":3,"file":"BaseService.js","sources":["../../src/services/BaseService.ts"],"sourcesContent":["/* eslint-disable import/no-unresolved */\n/* eslint-disable no-useless-catch */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-useless-constructor */\n/* eslint-disable no-empty-function */\nimport { FilterQuery } from 'mongoose';\nimport { injectable } from 'inversify';\nimport { GetAllArgs, IBaseMongoRepository, IBaseService, AsDomainType, CreateType, UpdateType } from 'common/server';\n\n@injectable()\nexport class BaseService2<SchemaType> implements IBaseService<SchemaType> {\n constructor(protected repository: IBaseMongoRepository<SchemaType>) {}\n\n async getAllWithCount(\n options: GetAllArgs<SchemaType>,\n ): Promise<{ data: AsDomainType<SchemaType>[]; totalCount: number }> {\n return this.repository.getAllWithCount(options);\n }\n\n count(conditions?: FilterQuery<SchemaType>): Promise<number> {\n return this.repository.count(conditions);\n }\n\n get(conditions: string | FilterQuery<SchemaType>): Promise<AsDomainType<SchemaType> | null> {\n if (typeof conditions === 'string') {\n return this.repository.get({ id: conditions } as FilterQuery<SchemaType>);\n }\n return this.repository.get(conditions);\n }\n\n getByName(name: string): Promise<AsDomainType<SchemaType> | null> {\n return this.repository.get({ name } as any);\n }\n\n getAll(options: GetAllArgs<SchemaType>): Promise<AsDomainType<SchemaType>[]> {\n return this.repository.getAll(options);\n }\n\n getByIds(ids: string[]): Promise<AsDomainType<SchemaType>[]> {\n return this.repository.bulkGet(ids);\n }\n\n create<T = CreateType<SchemaType>>(data: T): Promise<AsDomainType<SchemaType>> {\n return this.repository.create(data);\n }\n\n bulkCreate<T = CreateType<SchemaType>>(data: T[]): Promise<AsDomainType<SchemaType>[]> {\n return this.repository.bulkCreate(data);\n }\n\n async update<T = UpdateType<SchemaType>>(\n id: string,\n data: T,\n overwrite = false,\n ): Promise<AsDomainType<SchemaType>> {\n return this.repository.update({ id } as any, data, { overwrite });\n }\n\n async insert<T = CreateType<SchemaType>>(\n data: T & { id?: string },\n overwrite = true,\n ): Promise<AsDomainType<SchemaType>> {\n const { id, ...rest } = data;\n\n if (id) {\n try {\n const existing = await this.repository.get({ id } as any);\n if (existing) {\n return this.update(id, rest as any, overwrite);\n }\n } catch (error) {\n // If not found, continue to create\n }\n }\n\n return this.create(rest as T);\n }\n\n delete(id: string | FilterQuery<SchemaType>): Promise<boolean> {\n if (typeof id === 'string') {\n return this.repository.delete({ id } as any);\n }\n return this.repository.delete(id);\n }\n\n bulkDelete(criteria: FilterQuery<SchemaType>): Promise<number> {\n return this.repository.bulkDelete(criteria);\n }\n}\n"],"names":[],"mappings":";AAUa,IAAA,YAAY,GAAlB,MAAM,YAAY,CAAA;AACC,IAAA,UAAA,CAAA;AAAtB,IAAA,WAAA,CAAsB,UAA4C,EAAA;QAA5C,IAAU,CAAA,UAAA,GAAV,UAAU,CAAkC;KAAI;IAEtE,MAAM,eAAe,CACjB,OAA+B,EAAA;QAE/B,OAAO,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;KACnD;AAED,IAAA,KAAK,CAAC,UAAoC,EAAA;QACtC,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;KAC5C;AAED,IAAA,GAAG,CAAC,UAA4C,EAAA;AAC5C,QAAA,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE;AAChC,YAAA,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,UAAU,EAA6B,CAAC,CAAC;SAC7E;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;KAC1C;AAED,IAAA,SAAS,CAAC,IAAY,EAAA;QAClB,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,IAAI,EAAS,CAAC,CAAC;KAC/C;AAED,IAAA,MAAM,CAAC,OAA+B,EAAA;QAClC,OAAO,IAAI,CAA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CAAC;SAChD;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;KACrC;AAED,IAAA,UAAU,CAAC,QAAiC,EAAA;QACxC,OAAO,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;KAC/C;EACJ;AA9EY,YAAY,GAAA,UAAA,CAAA;AADxB,IAAA,UAAU,EAAE;AAEyB,IAAA,UAAA,CAAA,mBAAA,EAAA,CAAA,QAAA,EAAA,GAAA,OAAA,oBAAoB,oBAApB,oBAAoB,CAAA,KAAA,UAAA,GAAA,EAAA,GAAA,MAAA,CAAA,CAAA;AAD7C,CAAA,EAAA,YAAY,CA8ExB"}
1
+ {"version":3,"file":"BaseService.js","sources":["../../src/services/BaseService.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\n/* eslint-disable import/no-unresolved */\n/* eslint-disable no-useless-catch */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-useless-constructor */\n/* eslint-disable no-empty-function */\nimport { FilterQuery } from 'mongoose';\nimport { injectable } from 'inversify';\nimport { GetAllArgs, IBaseMongoRepository, IBaseService, AsDomainType, CreateType, UpdateType } from 'common/server';\n\n@injectable()\nexport class BaseService2<SchemaType, C = CreateType<SchemaType>, U = UpdateType<SchemaType>>\n implements IBaseService<SchemaType, C, U>\n{\n constructor(protected repository: IBaseMongoRepository<SchemaType>) {}\n\n async getAllWithCount(\n options: GetAllArgs<SchemaType>,\n ): Promise<{ data: AsDomainType<SchemaType>[]; totalCount: number }> {\n return this.repository.getAllWithCount(options);\n }\n\n count(conditions?: FilterQuery<SchemaType>): Promise<number> {\n return this.repository.count(conditions);\n }\n\n get(conditions: string | FilterQuery<SchemaType>): Promise<AsDomainType<SchemaType> | null> {\n if (typeof conditions === 'string') {\n return this.repository.get({ id: conditions } as FilterQuery<SchemaType>);\n }\n return this.repository.get(conditions);\n }\n\n getByName(name: string): Promise<AsDomainType<SchemaType> | null> {\n return this.repository.get({ name } as any);\n }\n\n getAll(options: GetAllArgs<SchemaType>): Promise<AsDomainType<SchemaType>[]> {\n return this.repository.getAll(options);\n }\n\n getByIds(ids: string[]): Promise<AsDomainType<SchemaType>[]> {\n return this.repository.bulkGet(ids);\n }\n\n create<T = CreateType<SchemaType>>(data: T): Promise<AsDomainType<SchemaType>> {\n return this.repository.create(data);\n }\n\n bulkCreate<T = CreateType<SchemaType>>(data: T[]): Promise<AsDomainType<SchemaType>[]> {\n return this.repository.bulkCreate(data);\n }\n\n async update<T = UpdateType<SchemaType>>(\n id: string,\n data: T,\n overwrite = false,\n ): Promise<AsDomainType<SchemaType>> {\n return this.repository.update({ id } as any, data, { overwrite });\n }\n\n async insert<T = CreateType<SchemaType>>(\n data: T & { id?: string },\n overwrite = true,\n ): Promise<AsDomainType<SchemaType>> {\n const { id, ...rest } = data;\n\n if (id) {\n try {\n const existing = await this.repository.get({ id } as any);\n if (existing) {\n return this.update(id, rest as any, overwrite);\n }\n } catch (error) {\n // If not found, continue to create\n }\n }\n\n return this.create(rest as T);\n }\n\n delete(id: string | FilterQuery<SchemaType>): Promise<boolean> {\n if (typeof id === 'string') {\n return this.repository.delete({ id } as any);\n }\n return this.repository.delete(id);\n }\n\n bulkDelete(criteria: FilterQuery<SchemaType>): Promise<number> {\n return this.repository.bulkDelete(criteria);\n }\n}\n"],"names":[],"mappings":";AAWa,IAAA,YAAY,GAAlB,MAAM,YAAY,CAAA;AAGC,IAAA,UAAA,CAAA;AAAtB,IAAA,WAAA,CAAsB,UAA4C,EAAA;QAA5C,IAAU,CAAA,UAAA,GAAV,UAAU,CAAkC;KAAI;IAEtE,MAAM,eAAe,CACjB,OAA+B,EAAA;QAE/B,OAAO,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;KACnD;AAED,IAAA,KAAK,CAAC,UAAoC,EAAA;QACtC,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;KAC5C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AI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,EAAE,EAAS,CAAC,CAAC;gBAC1D,IAAI,QAAQ,EAAE;oBACV,OAAO,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,IAAW,EAAE,SAAS,CAAC,CAAC;iBAClD;aACJ;YAAC,OAAO,KAAK,EAAE;;aAEf;SACJ;AAED,QAAA,OAAO,IAAI,CAAC,MAAM,CAAC,IAAS,CAAC,CAAC;KACjC;AAED,IAAA,MAAM,CAAC,EAAoC,EAAA;AACvC,QAAA,IAAI,OAAO,EAAE,KAAK,QAAQ,EAAE;YACxB,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,EAAE,EAAS,CAAC,CAAC;SAChD;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;KACrC;AAED,IAAA,UAAU,CAAC,QAAiC,EAAA;QACxC,OAAO,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;KAC/C;EACJ;AAhFY,YAAY,GAAA,UAAA,CAAA;AADxB,IAAA,UAAU,EAAE;AAIyB,IAAA,UAAA,CAAA,mBAAA,EAAA,CAAA,QAAA,EAAA,GAAA,OAAA,oBAAoB,oBAApB,oBAAoB,CAAA,KAAA,UAAA,GAAA,EAAA,GAAA,MAAA,CAAA,CAAA;AAH7C,CAAA,EAAA,YAAY,CAgFxB"}
@@ -1,7 +1,8 @@
1
1
  import { ServiceBroker } from 'moleculer';
2
2
  import { FilterQuery } from 'mongoose';
3
3
  import { CdmLogger } from '@cdm-logger/core';
4
- import { GetAllArgs, IBaseService } from '../interfaces';
4
+ import { GetAllArgs } from '../interfaces';
5
+ import { IBaseService } from '../interfaces/index.old';
5
6
  type MethodsNames<T, C, U> = keyof IBaseService<T, C, U>;
6
7
  type MethodResponse<T, C, U, M extends MethodsNames<T, C, U>> = ReturnType<IBaseService<T, C, U>[M]>;
7
8
  export declare abstract class BaseProxyService<T, C = T, U = T> implements IBaseService<T, C, U> {
@@ -1 +1 @@
1
- {"version":3,"file":"base-proxy-service.js","sources":["../../src/services/base-proxy-service.ts"],"sourcesContent":["import { inject, injectable, optional } from 'inversify';\nimport { ServiceBroker } from 'moleculer';\nimport { FilterQuery } from 'mongoose';\nimport { CdmLogger } from '@cdm-logger/core';\nimport { CommonType } from '@common-stack/core';\nimport { BaseServiceCommands } from 'common';\nimport { GetAllArgs, IBaseService } from '../interfaces';\n\ntype MethodsNames<T, C, U> = keyof IBaseService<T, C, U>;\ntype MethodResponse<T, C, U, M extends MethodsNames<T, C, U>> = ReturnType<IBaseService<T, C, U>[M]>;\n\n@injectable()\nexport abstract class BaseProxyService<T, C = T, U = T> implements IBaseService<T, C, U> {\n protected abstract logger?: CdmLogger.ILogger;\n\n protected abstract topic;\n\n constructor(\n @inject(CommonType.MOLECULER_BROKER)\n private readonly broker: ServiceBroker,\n @inject(CommonType.LOGGER)\n @optional()\n logger: CdmLogger.ILogger,\n ) {}\n\n getByName(name: string): Promise<T> {\n return this.callAction(BaseServiceCommands.GetByName, { name });\n }\n\n bulkCreate(data: C[]): MethodResponse<T, C, U, 'bulkCreate'> {\n return this.callAction<T[], { data: C[] }>(BaseServiceCommands.BulkCreate, { data });\n }\n\n count(criteria?: FilterQuery<Document>): MethodResponse<T, C, U, 'count'> {\n return this.callAction(BaseServiceCommands.Count, { criteria });\n }\n\n create(data: C): MethodResponse<T, C, U, 'create'> {\n return this.callAction(BaseServiceCommands.Create, { data });\n }\n\n delete(id: string | FilterQuery<Document>): MethodResponse<T, C, U, 'delete'> {\n return this.callAction(BaseServiceCommands.Delete, { id });\n }\n\n get(id?: string | FilterQuery<Document>): MethodResponse<T, C, U, 'get'> {\n return this.callAction(BaseServiceCommands.Get, { id });\n }\n\n getAll(options?: GetAllArgs<Document>): MethodResponse<T, C, U, 'getAll'> {\n return this.callAction(BaseServiceCommands.GetAll, options);\n }\n\n getByIds(ids: string[]): Promise<T[]> {\n return this.callAction(BaseServiceCommands.GetByIds, { ids });\n }\n\n getAllWithCount(options: GetAllArgs<Document>): MethodResponse<T, C, U, 'getAllWithCount'> {\n return this.callAction(BaseServiceCommands.GetAllWithCount, options);\n }\n\n insert(data: C | U, overwrite?: boolean): MethodResponse<T, C, U, 'insert'> {\n return this.callAction(BaseServiceCommands.Insert, { data, overwrite });\n }\n\n update(id: string, data: U, overwrite?: boolean): MethodResponse<T, C, U, 'update'> {\n return this.callAction<T>(BaseServiceCommands.Update, { id, data, overwrite });\n }\n\n protected async callAction<T, P = unknown>(command: string, params?: P): Promise<T> {\n return this.broker.call<T, P>(`${this.topic}.${command}`, params);\n }\n}\n"],"names":[],"mappings":"yPAYsB,IAAA,gBAAgB,GAA/B,MAAe,gBAAgB,CAAA;AAOb,IAAA,MAAA,CAAA;IAFrB,WAEqB,CAAA,MAAqB,EAGtC,MAAyB,EAAA;QAHR,IAAM,CAAA,MAAA,GAAN,MAAM,CAAe;KAItC;AAEJ,IAAA,SAAS,CAAC,IAAY,EAAA;AAClB,QAAA,OAAO,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,SAAS,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;KACnE;AAED,IAAA,UAAU,CAAC,IAAS,EAAA;AAChB,QAAA,OAAO,IAAI,CAAC,UAAU,CAAqB,mBAAmB,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;KACxF;AAED,IAAA,KAAK,CAAC,QAAgC,EAAA;AAClC,QAAA,OAAO,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,KAAK,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;KACnE;AAED,IAAA,MAAM,CAAC,IAAO,EAAA;AACV,QAAA,OAAO,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;KAChE;AAED,IAAA,MAAM,CAAC,EAAkC,EAAA;AACrC,QAAA,OAAO,IAAI,CAAC,UAAU,CAAC,mBAA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A,MAAM,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAA;AAEnC,IAAA,OAAA,CAAA,CAAA,EAAA,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;IACzB,OAAA,CAAA,CAAA,EAAA,QAAQ,EAAE,CAAA;qCAFc,aAAa,EAAA,MAAA,CAAA,CAAA;AAPxB,CAAA,EAAA,gBAAgB,CA4DrC"}
1
+ {"version":3,"file":"base-proxy-service.js","sources":["../../src/services/base-proxy-service.ts"],"sourcesContent":["import { inject, injectable, optional } from 'inversify';\nimport { ServiceBroker } from 'moleculer';\nimport { FilterQuery } from 'mongoose';\nimport { CdmLogger } from '@cdm-logger/core';\nimport { CommonType } from '@common-stack/core';\nimport { BaseServiceCommands } from 'common';\nimport { GetAllArgs } from '../interfaces';\nimport { IBaseService } from '../interfaces/index.old';\n\ntype MethodsNames<T, C, U> = keyof IBaseService<T, C, U>;\ntype MethodResponse<T, C, U, M extends MethodsNames<T, C, U>> = ReturnType<IBaseService<T, C, U>[M]>;\n\n@injectable()\nexport abstract class BaseProxyService<T, C = T, U = T> implements IBaseService<T, C, U> {\n protected abstract logger?: CdmLogger.ILogger;\n\n protected abstract topic;\n\n constructor(\n @inject(CommonType.MOLECULER_BROKER)\n private readonly broker: ServiceBroker,\n @inject(CommonType.LOGGER)\n @optional()\n logger: CdmLogger.ILogger,\n ) {}\n\n getByName(name: string): Promise<T> {\n return this.callAction(BaseServiceCommands.GetByName, { name });\n }\n\n bulkCreate(data: C[]): MethodResponse<T, C, U, 'bulkCreate'> {\n return this.callAction<T[], { data: C[] }>(BaseServiceCommands.BulkCreate, { data });\n }\n\n count(criteria?: FilterQuery<Document>): MethodResponse<T, C, U, 'count'> {\n return this.callAction(BaseServiceCommands.Count, { criteria });\n }\n\n create(data: C): MethodResponse<T, C, U, 'create'> {\n return this.callAction(BaseServiceCommands.Create, { data });\n }\n\n delete(id: string | FilterQuery<Document>): MethodResponse<T, C, U, 'delete'> {\n return this.callAction(BaseServiceCommands.Delete, { id });\n }\n\n get(id?: string | FilterQuery<Document>): MethodResponse<T, C, U, 'get'> {\n return this.callAction(BaseServiceCommands.Get, { id });\n }\n\n getAll(options?: GetAllArgs<Document>): MethodResponse<T, C, U, 'getAll'> {\n return this.callAction(BaseServiceCommands.GetAll, options);\n }\n\n getByIds(ids: string[]): Promise<T[]> {\n return this.callAction(BaseServiceCommands.GetByIds, { ids });\n }\n\n getAllWithCount(options: GetAllArgs<Document>): MethodResponse<T, C, U, 'getAllWithCount'> {\n return this.callAction(BaseServiceCommands.GetAllWithCount, options);\n }\n\n insert(data: C | U, overwrite?: boolean): MethodResponse<T, C, U, 'insert'> {\n return this.callAction(BaseServiceCommands.Insert, { data, overwrite });\n }\n\n update(id: string, data: U, overwrite?: boolean): MethodResponse<T, C, U, 'update'> {\n return this.callAction<T>(BaseServiceCommands.Update, { id, data, overwrite });\n }\n\n protected async callAction<T, P = unknown>(command: string, params?: P): Promise<T> {\n return this.broker.call<T, P>(`${this.topic}.${command}`, params);\n }\n}\n"],"names":[],"mappings":"yPAasB,IAAA,gBAAgB,GAA/B,MAAe,gBAAgB,CAAA;AAOb,IAAA,MAAA,CAAA;IAFrB,WAEqB,CAAA,MAAqB,EAGtC,MAAyB,EAAA;QAHR,IAAM,CAAA,MAAA,GAAN,MAAM,CAAe;KAItC;AAEJ,IAAA,SAAS,CAAC,IAAY,EAAA;AAClB,QAAA,OAAO,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,SAAS,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;KACnE;AAED,IAAA,UAAU,CAAC,IAAS,EAAA;AAChB,QAAA,OAAO,IAAI,CAAC,UAAU,CAAqB,mBAAmB,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;KACxF;AAED,IAAA,KAAK,CAAC,QAAgC,EAAA;AAClC,QAAA,OAAO,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,KAAK,EAAE,EAAE,QAAQ,EAAE,CAA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ClE,QAAA,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAO,CAAG,EAAA,IAAI,CAAC,KAAK,IAAI,OAAO,CAAA,CAAE,EAAE,MAAM,CAAC,CAAC;KACrE;EACJ;AA5DqB,gBAAgB,GAAA,UAAA,CAAA;AADrC,IAAA,UAAU,EAAE;AAOJ,IAAA,OAAA,CAAA,CAAA,EAAA,MAAM,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAA;AAEnC,IAAA,OAAA,CAAA,CAAA,EAAA,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;IACzB,OAAA,CAAA,CAAA,EAAA,QAAQ,EAAE,CAAA;qCAFc,aAAa,EAAA,MAAA,CAAA,CAAA;AAPxB,CAAA,EAAA,gBAAgB,CA4DrC"}
@@ -1,5 +1,6 @@
1
1
  import { Document, FilterQuery } from 'mongoose';
2
- import { GetAllArgs, IBaseRepository, IBaseService } from '../interfaces';
2
+ import { GetAllArgs } from '../interfaces';
3
+ import { IBaseRepository, IBaseService } from '../interfaces/index.old';
3
4
  export declare class BaseService<T, C = Omit<T, 'id'>, U = C> implements IBaseService<T, C, U> {
4
5
  protected repository: IBaseRepository<T>;
5
6
  constructor(repository: IBaseRepository<T>);
@@ -1 +1 @@
1
- {"version":3,"file":"base-service.js","sources":["../../src/services/base-service.ts"],"sourcesContent":["import { Document, FilterQuery } from 'mongoose';\nimport { injectable } from 'inversify';\nimport { GetAllArgs, IBaseRepository, IBaseService } from '../interfaces';\n\n@injectable()\nexport class BaseService<T, C = Omit<T, 'id'>, U = C> implements IBaseService<T, C, U> {\n constructor(protected repository: IBaseRepository<T>) {\n this.repository = repository;\n }\n\n async getAllWithCount(options: GetAllArgs<Document<T>>): Promise<{ data: T[]; totalCount: number }> {\n const totalCount = await this.count(options.criteria);\n const data = await this.getAll(options);\n return {\n totalCount,\n data,\n };\n }\n\n count(conditions?: FilterQuery<Document<T>>): Promise<number> {\n return this.repository.count(conditions);\n }\n\n get(conditions: string | FilterQuery<Document<T>>): Promise<T> {\n if (typeof conditions === 'string') {\n return this.repository.get({ id: conditions });\n }\n return this.repository.get(conditions);\n }\n\n getByName(name: string): Promise<T> {\n return this.repository.get({ name });\n }\n\n getAll(options: GetAllArgs<Document<T>>): Promise<T[]> {\n return this.repository.getAll(options);\n }\n\n getByIds(ids: string[]): Promise<T[]> {\n return this.repository.bulkGet(ids);\n }\n\n create(data: C): Promise<T> {\n return this.repository.create<C>(data);\n }\n\n bulkCreate(data: C[]): Promise<T[]> {\n return this.repository.bulkCreate<C>(data);\n }\n\n async update(id: string, data: Partial<U>, overwrite = false): Promise<T> {\n return this.repository.update<U>({ id }, data, { overwrite });\n }\n\n insert(data: (C | U) & { id?: string }, overwrite = true): Promise<T> {\n const { id, ...rest } = data;\n if (id) {\n const existing = this.repository.get({ id });\n if (existing) {\n return this.update(id, rest as U, overwrite);\n }\n }\n return this.create(rest as C);\n }\n\n delete(id: string | FilterQuery<Document<T>>): Promise<boolean> {\n if (typeof id === 'string') {\n return this.repository.delete({ id });\n }\n return this.repository.delete(id);\n }\n}\n"],"names":[],"mappings":"6EAKa,IAAA,WAAW,GAAjB,MAAM,WAAW,CAAA;AACE,IAAA,UAAA,CAAA;AAAtB,IAAA,WAAA,CAAsB,UAA8B,EAAA;QAA9B,IAAU,CAAA,UAAA,GAAV,UAAU,CAAoB;AAChD,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;KAChC;IAED,MAAM,eAAe,CAAC,OAAgC,EAAA;QAClD,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACtD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACxC,OAAO;YACH,UAAU;YACV,IAAI;SACP,CAAC;KACL;AAED,IAAA,KAAK,CAAC,UAAqC,EAAA;QACvC,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC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,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;YAC7C,IAAI,QAAQ,EAAE;gBACV,OAAO,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,IAAS,EAAE,SAAS,CAAC,CAAC;aAChD;SACJ;AACD,QAAA,OAAO,IAAI,CAAC,MAAM,CAAC,IAAS,CAAC,CAAC;KACjC;AAED,IAAA,MAAM,CAAC,EAAqC,EAAA;AACxC,QAAA,IAAI,OAAO,EAAE,KAAK,QAAQ,EAAE;YACxB,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;SACzC;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;KACrC;EACJ;AAlEY,WAAW,GAAA,UAAA,CAAA;AADvB,IAAA,UAAU,EAAE;;AACA,CAAA,EAAA,WAAW,CAkEvB"}
1
+ {"version":3,"file":"base-service.js","sources":["../../src/services/base-service.ts"],"sourcesContent":["import { Document, FilterQuery } from 'mongoose';\nimport { injectable } from 'inversify';\nimport { GetAllArgs } from '../interfaces';\nimport { IBaseRepository, IBaseService } from '../interfaces/index.old';\n\n@injectable()\nexport class BaseService<T, C = Omit<T, 'id'>, U = C> implements IBaseService<T, C, U> {\n constructor(protected repository: IBaseRepository<T>) {\n this.repository = repository;\n }\n\n async getAllWithCount(options: GetAllArgs<Document<T>>): Promise<{ data: T[]; totalCount: number }> {\n const totalCount = await this.count(options.criteria);\n const data = await this.getAll(options);\n return {\n totalCount,\n data,\n };\n }\n\n count(conditions?: FilterQuery<Document<T>>): Promise<number> {\n return this.repository.count(conditions);\n }\n\n get(conditions: string | FilterQuery<Document<T>>): Promise<T> {\n if (typeof conditions === 'string') {\n return this.repository.get({ id: conditions });\n }\n return this.repository.get(conditions);\n }\n\n getByName(name: string): Promise<T> {\n return this.repository.get({ name });\n }\n\n getAll(options: GetAllArgs<Document<T>>): Promise<T[]> {\n return this.repository.getAll(options);\n }\n\n getByIds(ids: string[]): Promise<T[]> {\n return this.repository.bulkGet(ids);\n }\n\n create(data: C): Promise<T> {\n return this.repository.create<C>(data);\n }\n\n bulkCreate(data: C[]): Promise<T[]> {\n return this.repository.bulkCreate<C>(data);\n }\n\n async update(id: string, data: Partial<U>, overwrite = false): Promise<T> {\n return this.repository.update<U>({ id }, data, { overwrite });\n }\n\n insert(data: (C | U) & { id?: string }, overwrite = true): Promise<T> {\n const { id, ...rest } = data;\n if (id) {\n const existing = this.repository.get({ id });\n if (existing) {\n return this.update(id, rest as U, overwrite);\n }\n }\n return this.create(rest as C);\n }\n\n delete(id: string | FilterQuery<Document<T>>): Promise<boolean> {\n if (typeof id === 'string') {\n return this.repository.delete({ id });\n }\n return this.repository.delete(id);\n }\n}\n"],"names":[],"mappings":"6EAMa,IAAA,WAAW,GAAjB,MAAM,WAAW,CAAA;AACE,IAAA,UAAA,CAAA;AAAtB,IAAA,WAAA,CAAsB,UAA8B,EAAA;QAA9B,IAAU,CAAA,UAAA,GAAV,UAAU,CAAoB;AAChD,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;KAChC;IAED,MAAM,eAAe,CAAC,OAAgC,EAAA;QAClD,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACtD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACxC,OAAO;YACH,UAAU;YACV,IAAI;SACP,CAAC;KACL;AAED,IAAA,KAAK,CAAC,UAAqC,EAAA;QACvC,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;KAC5C;AAED,IAAA,GAAG,CAAC,UAA6C,EAAA;AAC7C,QAAA,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE;AAChC,YAAA,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;SAClD;QACD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CAAC,CAAC;KACjC;AAED,IAAA,MAAM,CAAC,EAAqC,EAAA;AACxC,QAAA,IAAI,OAAO,EAAE,KAAK,QAAQ,EAAE;YACxB,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;SACzC;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;KACrC;EACJ;AAlEY,WAAW,GAAA,UAAA,CAAA;AADvB,IAAA,UAAU,EAAE;;AACA,CAAA,EAAA,WAAW,CAkEvB"}
@@ -5,8 +5,15 @@ export declare class BaseMongoRepository<SchemaType> implements IBaseMongoReposi
5
5
  private modelFunc;
6
6
  private options;
7
7
  protected logger: CdmLogger.ILogger;
8
- model: Model<SchemaType>;
8
+ model: Model<SchemaType & {
9
+ id: string;
10
+ }>;
9
11
  constructor(modelFunc: (db: Connection) => Model<SchemaType>, db: Connection, logger: CdmLogger.ILogger, options?: IMongoOptions);
12
+ /**
13
+ * Safely registers or retrieves a Mongoose model to prevent overwrite errors
14
+ * This is crucial for development environments where multiple containers might try to register the same model
15
+ */
16
+ private safeModelRegistration;
10
17
  /**
11
18
  * Transforms a document to the domain model format
12
19
  */
@@ -1,14 +1,44 @@
1
- import {__decorate,__param,__metadata}from'tslib';import {isObject}from'lodash-es';import'@cdm-logger/core';import {Connection,Types}from'mongoose';import {injectable,unmanaged}from'inversify';import {IMongoOptions,PAGINATION_OPTIONS}from'common/server';var _a;
2
- let BaseMongoRepository = class BaseMongoRepository {
1
+ import {__decorate,__param,__metadata}from'tslib';import {isObject}from'lodash-es';import'@cdm-logger/core';import {Connection,Types}from'mongoose';import {injectable,unmanaged}from'inversify';import {IMongoOptions,PAGINATION_OPTIONS}from'common/server';var BaseMongoRepository_1;
2
+ var _a;
3
+ let BaseMongoRepository = BaseMongoRepository_1 = class BaseMongoRepository {
3
4
  modelFunc;
4
5
  options;
5
6
  logger;
6
7
  model;
7
8
  constructor(modelFunc, db, logger, options) {
8
9
  this.modelFunc = modelFunc;
9
- this.model = modelFunc(db);
10
+ // Safe model registration to prevent "Cannot overwrite model once compiled" errors
11
+ this.model = this.safeModelRegistration(db);
10
12
  this.options = options;
11
- this.logger = logger.child({ className: BaseRepository2.name });
13
+ this.logger = logger.child({ className: BaseMongoRepository_1.name });
14
+ }
15
+ /**
16
+ * Safely registers or retrieves a Mongoose model to prevent overwrite errors
17
+ * This is crucial for development environments where multiple containers might try to register the same model
18
+ */
19
+ safeModelRegistration(db) {
20
+ try {
21
+ return this.modelFunc(db);
22
+ }
23
+ catch (error) {
24
+ // If the error is about overwriting a model, try to get the existing model
25
+ if (error instanceof Error && error.message.includes('Cannot overwrite')) {
26
+ // Extract model name from the error message or try to infer it
27
+ const modelNameMatch = error.message.match(/Cannot overwrite `(\w+)` model/);
28
+ if (modelNameMatch) {
29
+ const modelName = modelNameMatch[1];
30
+ try {
31
+ return db.model(modelName);
32
+ }
33
+ catch (getError) {
34
+ // If we can't get the existing model, re-throw the original error
35
+ throw error;
36
+ }
37
+ }
38
+ }
39
+ // For any other error, re-throw it
40
+ throw error;
41
+ }
12
42
  }
13
43
  /**
14
44
  * Transforms a document to the domain model format
@@ -356,7 +386,7 @@ let BaseMongoRepository = class BaseMongoRepository {
356
386
  // Create a query that handles both ObjectId and string IDs
357
387
  const query = { _id: { $in: [] } };
358
388
  // Process each ID
359
- ids.forEach((id) => {
389
+ ids?.forEach((id) => {
360
390
  if (Types.ObjectId.isValid(id)) {
361
391
  query._id.$in.push(new Types.ObjectId(id));
362
392
  }
@@ -364,7 +394,12 @@ let BaseMongoRepository = class BaseMongoRepository {
364
394
  query._id.$in.push(id); // Add as string
365
395
  }
366
396
  });
367
- const results = await this.model.find(query).select(selectedFields).lean().exec();
397
+ let findQuery = this.model.find(query);
398
+ // apply select if selectedFields is provided
399
+ if (selectedFields) {
400
+ findQuery = findQuery.select(selectedFields);
401
+ }
402
+ const results = await findQuery.lean().exec();
368
403
  // Ensure id exists for each document
369
404
  return results.map((doc) => {
370
405
  if (doc._id && !doc.id) {
@@ -379,10 +414,9 @@ let BaseMongoRepository = class BaseMongoRepository {
379
414
  }
380
415
  }
381
416
  };
382
- BaseMongoRepository = __decorate([
417
+ BaseMongoRepository = BaseMongoRepository_1 = __decorate([
383
418
  injectable(),
384
419
  __param(0, unmanaged()),
385
- __param(1, unmanaged()),
386
420
  __param(2, unmanaged()),
387
421
  __param(3, unmanaged()),
388
422
  __metadata("design:paramtypes", [Function, Connection, Object, typeof (_a = typeof IMongoOptions !== "undefined" && IMongoOptions) === "function" ? _a : Object])
@@ -1 +1 @@
1
- {"version":3,"file":"BaseMongoRepository.js","sources":["../../../src/store/repositories/BaseMongoRepository.ts"],"sourcesContent":["/* eslint-disable import/no-unresolved */\n/* eslint-disable import/no-extraneous-dependencies */\n/* eslint-disable no-param-reassign */\n/* eslint-disable no-underscore-dangle */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable class-methods-use-this */\nimport { isObject } from 'lodash-es';\nimport { CdmLogger } from '@cdm-logger/core';\nimport { Connection, FilterQuery, Model, PipelineStage, Types, UpdateQuery } from 'mongoose';\nimport { injectable, unmanaged } from 'inversify';\nimport {\n GetAllArgs,\n ISort,\n IBaseMongoRepository,\n IMongoOptions,\n PAGINATION_OPTIONS,\n AsDomainType,\n CreateType,\n UpdateType,\n} from 'common/server';\n\n@injectable()\nexport class BaseMongoRepository<SchemaType> implements IBaseMongoRepository<SchemaType> {\n private options: IMongoOptions;\n\n protected logger: CdmLogger.ILogger;\n\n model: Model<SchemaType>;\n\n constructor(\n @unmanaged()\n private modelFunc: (db: Connection) => Model<SchemaType>,\n @unmanaged()\n db: Connection,\n @unmanaged()\n logger: CdmLogger.ILogger,\n @unmanaged()\n options?: IMongoOptions,\n ) {\n this.model = modelFunc(db);\n this.options = options;\n this.logger = logger.child({ className: BaseRepository2.name });\n }\n\n /**\n * Transforms a document to the domain model format\n */\n protected transformDocument(doc: any): AsDomainType<SchemaType> | null {\n if (!doc) return null;\n\n // If it's already a plain object (not a Mongoose document)\n if (!doc.toObject) {\n // Ensure id exists if _id is present\n if (doc._id && !doc.id) {\n doc.id = typeof doc._id === 'object' && doc._id.toString ? doc._id.toString() : doc._id;\n }\n return doc as AsDomainType<SchemaType>;\n }\n\n // For Mongoose documents, use the built-in toObject transformation\n return doc.toObject() as AsDomainType<SchemaType>;\n }\n\n /**\n * Transforms an array of documents\n */\n protected transformDocuments(docs: SchemaType[]): AsDomainType<SchemaType>[] {\n if (!docs || !Array.isArray(docs)) return [];\n return docs.map((doc) => this.transformDocument(doc)).filter(Boolean) as AsDomainType<SchemaType>[];\n }\n\n /**\n * Maps API criteria with 'id' to MongoDB criteria with '_id'\n */\n private mapConditions(conditions?: FilterQuery<SchemaType>): FilterQuery<SchemaType> {\n if (!conditions) return {};\n\n const { id, ...remaining } = conditions as any;\n\n if (!id) return remaining as FilterQuery<SchemaType>;\n\n // Handle custom _id that might not be an ObjectId\n let _id;\n if (Types.ObjectId.isValid(id)) {\n _id = new Types.ObjectId(id);\n } else {\n _id = id; // Use the id as-is if it's not a valid ObjectId\n }\n\n return {\n _id,\n ...remaining,\n } as FilterQuery<SchemaType>;\n }\n\n /**\n * Computes sort object from GetAllArgs sort parameter\n * Handles both string-based and object-based sort specifications\n */\n protected computeSort(sort: ISort | string | ISort[]): Record<string, 1 | -1> {\n // Default sort by createdAt descending if available, otherwise empty sort\n if (!sort) {\n return { createdAt: -1 };\n }\n\n // Handle object-based sort { key: 'fieldName', value: 'asc'|'desc' }\n if (isObject(sort) && 'key' in sort) {\n return {\n [sort.key]: sort.value?.toLowerCase() === 'asc' ? 1 : -1,\n };\n }\n\n // Handle string-based sort 'fieldName:asc' or 'fieldName:desc'\n if (typeof sort === 'string') {\n const [field, direction] = sort.split(':');\n if (field) {\n return {\n [field]: direction?.toLowerCase() === 'asc' ? 1 : -1,\n };\n }\n }\n\n // Handle array of sort specifications\n if (Array.isArray(sort)) {\n return sort.reduce((acc, sortItem) => {\n if (isObject(sortItem) && sortItem.key) {\n acc[sortItem.key] = sortItem.value?.toLowerCase() === 'asc' ? 1 : -1;\n }\n return acc;\n }, {});\n }\n\n // Fallback to default sort\n return { createdAt: -1 };\n }\n\n /**\n * Prepares an aggregation pipeline with standard stages\n * @param options Query options including filtering, sorting, pagination\n * @param customPipeline Optional custom pipeline stages to include\n * @returns Complete MongoDB aggregation pipeline\n */\n protected preparePipeline(options: GetAllArgs<SchemaType>, customPipeline: PipelineStage[] = []): PipelineStage[] {\n const { criteria, sort, limit, skip } = options;\n const pipeline: PipelineStage[] = [];\n\n // Match stage (filtering)\n if (criteria) {\n pipeline.push({\n $match: this.mapConditions(criteria),\n });\n }\n\n // Add custom pipeline stages\n if (customPipeline.length > 0) {\n pipeline.push(...customPipeline);\n }\n\n // Sort stage\n const sortBy = this.computeSort(sort);\n if (Object.keys(sortBy).length > 0) {\n pipeline.push({ $sort: sortBy });\n }\n\n // Pagination stages\n if (skip !== undefined) {\n pipeline.push({ $skip: skip || PAGINATION_OPTIONS.skip });\n }\n\n if (limit !== undefined) {\n pipeline.push({ $limit: limit || PAGINATION_OPTIONS.limit });\n }\n\n return pipeline;\n }\n\n /**\n * Execute an aggregation pipeline and transform the results\n */\n protected async aggregate(pipeline: PipelineStage[]): Promise<AsDomainType<SchemaType>[]> {\n try {\n const results = await this.model.aggregate(pipeline).exec();\n return this.transformDocuments(results);\n } catch (e) {\n this.logger.error(e, 'Error executing aggregation pipeline: %j', pipeline);\n throw e;\n }\n }\n\n public async count(conditions?: FilterQuery<SchemaType>): Promise<number> {\n return this.model.count(this.mapConditions(conditions)).exec();\n }\n\n public async get(\n conditions?: FilterQuery<SchemaType>,\n selectedFields?: string,\n ): Promise<AsDomainType<SchemaType> | null> {\n try {\n const response = await this.model.findOne(this.mapConditions(conditions), selectedFields).lean().exec();\n\n if (!response) return null;\n\n // Ensure id exists\n if (response && (response as any)._id && !(response as any).id) {\n (response as any).id = (response as any)._id.toString();\n }\n\n return response as AsDomainType<SchemaType>;\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', conditions);\n throw e;\n }\n }\n\n public async find(\n conditions: Partial<FilterQuery<SchemaType>>,\n selectedFields?: string,\n ): Promise<AsDomainType<SchemaType> | null> {\n try {\n const response = await this.model.findOne(conditions, selectedFields).lean().exec();\n\n if (!response) return null;\n\n // Ensure id exists\n if (response && (response as any)._id && !(response as any).id) {\n (response as any).id = (response as any)._id.toString();\n }\n\n return response as AsDomainType<SchemaType>;\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', conditions);\n throw e;\n }\n }\n\n public async getAll(options: GetAllArgs<SchemaType>): Promise<AsDomainType<SchemaType>[]> {\n try {\n const { criteria, selectedFields, sort, limit, skip } = options;\n const mappedCriteria = this.mapConditions(criteria);\n const sortBy = this.computeSort(sort);\n\n const response = await this.model\n .find(mappedCriteria, selectedFields)\n .sort(sortBy as any)\n .limit(limit || PAGINATION_OPTIONS.limit)\n .skip(skip || PAGINATION_OPTIONS.skip)\n .lean()\n .exec();\n\n // Ensure id exists for each document\n return response.map((doc) => {\n if (doc._id && !doc.id) {\n doc.id = doc._id.toString();\n }\n return doc as AsDomainType<SchemaType>;\n });\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', options);\n throw e;\n }\n }\n\n /**\n * Get all documents using aggregation pipeline\n */\n public async getAllWithPipeline(\n options: GetAllArgs<SchemaType>,\n customPipeline: PipelineStage[] = [],\n ): Promise<AsDomainType<SchemaType>[]> {\n try {\n const pipeline = this.preparePipeline(options, customPipeline);\n return this.aggregate(pipeline);\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with pipeline [%j]', customPipeline);\n throw e;\n }\n }\n\n public async getAllWithCount(options: GetAllArgs<SchemaType>): Promise<{\n data: AsDomainType<SchemaType>[];\n totalCount: number;\n }> {\n const data = await this.getAll(options);\n const totalCount = await this.count(options.criteria);\n return { totalCount, data };\n }\n\n /**\n * Get all documents with count using aggregation pipeline\n */\n public async getAllWithCountAndPipeline(\n options: GetAllArgs<SchemaType>,\n customPipeline: PipelineStage[] = [],\n ): Promise<{\n data: AsDomainType<SchemaType>[];\n totalCount: number;\n }> {\n // Clone options to avoid modifying the original\n const countOptions = { ...options };\n\n // Remove pagination for count\n delete countOptions.limit;\n delete countOptions.skip;\n\n // Prepare count pipeline (without pagination)\n const countPipeline = this.preparePipeline(countOptions, customPipeline);\n countPipeline.push({ $count: 'total' });\n\n // Execute both queries in parallel\n const [data, countResult] = await Promise.all([\n this.getAllWithPipeline(options, customPipeline),\n this.model.aggregate(countPipeline).exec(),\n ]);\n\n const totalCount = countResult?.[0]?.total || 0;\n return { data, totalCount };\n }\n\n public async create<T = CreateType<SchemaType>>(data: T): Promise<AsDomainType<SchemaType>> {\n try {\n // Handle custom _id if provided in the data\n const createData = { ...data } as any;\n\n // If id is provided but _id is not, map id to _id\n if (createData.id && !createData._id) {\n createData._id = Types.ObjectId.isValid(createData.id)\n ? new Types.ObjectId(createData.id)\n : createData.id;\n delete createData.id; // Remove id to avoid conflicts\n }\n\n const response = await this.model.create(createData);\n return this.transformDocument(response);\n } catch (e) {\n this.logger.error(e, 'Unable to create Model with data [%j]', data);\n throw e;\n }\n }\n\n public async bulkCreate<T = CreateType<SchemaType>>(data: T[]): Promise<AsDomainType<SchemaType>[]> {\n try {\n const response = await this.model.insertMany(data, {\n lean: true,\n ordered: true,\n });\n\n // Ensure id exists for each document\n return response.map((doc: any) => {\n if (doc._id && !doc.id) {\n doc.id = doc._id.toString();\n }\n return doc as AsDomainType<SchemaType>;\n });\n } catch (e) {\n this.logger.error(e, 'Unable to bulk create due to error [%s]', e.message);\n throw e;\n }\n }\n\n public async upsert<T = UpdateType<SchemaType>>(\n conditions: FilterQuery<SchemaType>,\n update: T,\n options: Record<string, unknown> = {},\n ): Promise<AsDomainType<SchemaType>> {\n return this.update(conditions, update, {\n upsert: true,\n ...options,\n });\n }\n\n public async update<T = UpdateType<SchemaType>>(\n criteria: FilterQuery<SchemaType>,\n update: T | UpdateQuery<SchemaType>,\n options: Record<string, unknown> = {},\n ): Promise<AsDomainType<SchemaType>> {\n try {\n const mappedCriteria = this.mapConditions(criteria);\n const mergedOptions = {\n new: true,\n useFindAndModify: false,\n ...options,\n };\n\n const { id } = criteria as any;\n let response;\n\n if (id) {\n response = await this.model.findByIdAndUpdate(id, update as any, mergedOptions).exec();\n } else {\n response = await this.model.findOneAndUpdate(mappedCriteria, update as any, mergedOptions).exec();\n }\n\n return this.transformDocument(response);\n } catch (e) {\n this.logger.error(e, 'Unable to Update with criteria [%j] and data [%j]', criteria, update);\n throw e;\n }\n }\n\n public async bulkUpdate<T = UpdateType<SchemaType>>(\n criteria: FilterQuery<SchemaType>,\n update: T | UpdateQuery<SchemaType>,\n options: Record<string, unknown> = {},\n ): Promise<AsDomainType<SchemaType>[]> {\n try {\n const mappedCriteria = this.mapConditions(criteria);\n await this.model.updateMany(mappedCriteria, update as any, options);\n\n // Fetch the updated documents\n const response = await this.model.find(mappedCriteria).lean().exec();\n\n // Ensure id exists for each document\n return response.map((doc) => {\n if (doc._id && !doc.id) {\n doc.id = doc._id.toString();\n }\n return doc as AsDomainType<SchemaType>;\n });\n } catch (e) {\n this.logger.error(e, 'Unable to Bulk Update with criteria [%j] and data [%j]', criteria, update);\n throw e;\n }\n }\n\n public async delete(criteria: FilterQuery<SchemaType>): Promise<boolean> {\n try {\n const mappedCriteria = this.mapConditions(criteria);\n let deleted;\n\n if (criteria?.id) {\n deleted = await this.model.findByIdAndDelete(criteria.id);\n } else {\n deleted = await this.model.findOneAndDelete(mappedCriteria);\n }\n\n return !!deleted;\n } catch (e) {\n this.logger.error(e, 'Unable to delete the model with criteria [%j]', criteria);\n throw e;\n }\n }\n\n public async bulkDelete(criteria: FilterQuery<SchemaType>): Promise<number> {\n try {\n const mappedCriteria = this.mapConditions(criteria);\n const deleted = await this.model.deleteMany(mappedCriteria);\n return deleted?.deletedCount || 0;\n } catch (e) {\n this.logger.error(e, 'Unable to delete the model with criteria [%j]', criteria);\n throw e;\n }\n }\n\n public async bulkGet(ids: string[], selectedFields?: string): Promise<AsDomainType<SchemaType>[]> {\n try {\n // Create a query that handles both ObjectId and string IDs\n const query: any = { _id: { $in: [] } };\n\n // Process each ID\n ids.forEach((id) => {\n if (Types.ObjectId.isValid(id)) {\n query._id.$in.push(new Types.ObjectId(id));\n } else {\n query._id.$in.push(id); // Add as string\n }\n });\n\n const results = await this.model.find(query).select(selectedFields).lean().exec();\n\n // Ensure id exists for each document\n return results.map((doc) => {\n if ((doc as any)._id && !(doc as any).id) {\n (doc as any).id = (doc as any)._id.toString();\n }\n return doc as AsDomainType<SchemaType>;\n });\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', ids);\n throw e;\n }\n }\n}\n"],"names":[],"mappings":";AAsBa,IAAA,mBAAmB,GAAzB,MAAM,mBAAmB,CAAA;AAShB,IAAA,SAAA,CAAA;AARJ,IAAA,OAAO,CAAgB;AAErB,IAAA,MAAM,CAAoB;AAEpC,IAAA,KAAK,CAAoB;AAEzB,IAAA,WAAA,CAEY,SAAgD,EAExD,EAAc,EAEd,MAAyB,EAEzB,OAAuB,EAAA;QANf,IAAS,CAAA,SAAA,GAAT,SAAS,CAAuC;AAQxD,QAAA,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,EAAE,CAAC,CAAC;AAC3B,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACvB,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,eAAe,CAAC,IAAI,EAAE,CAAC,CAAC;KACnE;AAED;;AAEG;AACO,IAAA,iBAAiB,CAAC,GAAQ,EAAA;AAChC,QAAA,IAAI,CAAC,GAAG;AAAE,YAAA,OAAO,IAAI,CAAC;;AAGtB,QAAA,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE;;YAEf,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,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/store/repositories/BaseMongoRepository.ts"],"sourcesContent":["/* eslint-disable import/no-unresolved */\n/* eslint-disable import/no-extraneous-dependencies */\n/* eslint-disable no-param-reassign */\n/* eslint-disable no-underscore-dangle */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable class-methods-use-this */\nimport { isObject } from 'lodash-es';\nimport { CdmLogger } from '@cdm-logger/core';\nimport { Connection, FilterQuery, Model, PipelineStage, Types, UpdateQuery } from 'mongoose';\nimport { injectable, unmanaged } from 'inversify';\nimport {\n GetAllArgs,\n ISort,\n IBaseMongoRepository,\n IMongoOptions,\n PAGINATION_OPTIONS,\n AsDomainType,\n CreateType,\n UpdateType,\n} from 'common/server';\n\n@injectable()\nexport class BaseMongoRepository<SchemaType> implements IBaseMongoRepository<SchemaType> {\n private options: IMongoOptions;\n\n protected logger: CdmLogger.ILogger;\n\n model: Model<SchemaType & { id: string }>;\n\n constructor(\n @unmanaged()\n private modelFunc: (db: Connection) => Model<SchemaType>,\n\n db: Connection,\n @unmanaged()\n logger: CdmLogger.ILogger,\n @unmanaged()\n options?: IMongoOptions,\n ) {\n // Safe model registration to prevent \"Cannot overwrite model once compiled\" errors\n this.model = this.safeModelRegistration(db) as Model<SchemaType & { id: string }>;\n this.options = options;\n this.logger = logger.child({ className: BaseMongoRepository.name });\n }\n\n /**\n * Safely registers or retrieves a Mongoose model to prevent overwrite errors\n * This is crucial for development environments where multiple containers might try to register the same model\n */\n private safeModelRegistration(db: Connection): Model<SchemaType> {\n try {\n return this.modelFunc(db);\n } catch (error) {\n // If the error is about overwriting a model, try to get the existing model\n if (error instanceof Error && error.message.includes('Cannot overwrite')) {\n // Extract model name from the error message or try to infer it\n const modelNameMatch = error.message.match(/Cannot overwrite `(\\w+)` model/);\n if (modelNameMatch) {\n const modelName = modelNameMatch[1];\n try {\n return db.model(modelName);\n } catch (getError) {\n // If we can't get the existing model, re-throw the original error\n throw error;\n }\n }\n }\n // For any other error, re-throw it\n throw error;\n }\n }\n\n /**\n * Transforms a document to the domain model format\n */\n protected transformDocument(doc: any): AsDomainType<SchemaType> | null {\n if (!doc) return null;\n\n // If it's already a plain object (not a Mongoose document)\n if (!doc.toObject) {\n // Ensure id exists if _id is present\n if (doc._id && !doc.id) {\n doc.id = typeof doc._id === 'object' && doc._id.toString ? doc._id.toString() : doc._id;\n }\n return doc as unknown as AsDomainType<SchemaType>;\n }\n\n // For Mongoose documents, use the built-in toObject transformation\n return doc.toObject() as AsDomainType<SchemaType>;\n }\n\n /**\n * Transforms an array of documents\n */\n protected transformDocuments(docs: SchemaType[]): AsDomainType<SchemaType>[] {\n if (!docs || !Array.isArray(docs)) return [];\n return docs.map((doc) => this.transformDocument(doc)).filter(Boolean) as AsDomainType<SchemaType>[];\n }\n\n /**\n * Maps API criteria with 'id' to MongoDB criteria with '_id'\n */\n private mapConditions(conditions?: FilterQuery<SchemaType>): FilterQuery<SchemaType> {\n if (!conditions) return {};\n\n const { id, ...remaining } = conditions as any;\n\n if (!id) return remaining as FilterQuery<SchemaType>;\n\n // Handle custom _id that might not be an ObjectId\n let _id;\n if (Types.ObjectId.isValid(id)) {\n _id = new Types.ObjectId(id);\n } else {\n _id = id; // Use the id as-is if it's not a valid ObjectId\n }\n\n return {\n _id,\n ...remaining,\n } as FilterQuery<SchemaType>;\n }\n\n /**\n * Computes sort object from GetAllArgs sort parameter\n * Handles both string-based and object-based sort specifications\n */\n protected computeSort(sort: ISort | string | ISort[]): Record<string, 1 | -1> {\n // Default sort by createdAt descending if available, otherwise empty sort\n if (!sort) {\n return { createdAt: -1 };\n }\n\n // Handle object-based sort { key: 'fieldName', value: 'asc'|'desc' }\n if (isObject(sort) && 'key' in sort) {\n return {\n [sort.key]: sort.value?.toLowerCase() === 'asc' ? 1 : -1,\n };\n }\n\n // Handle string-based sort 'fieldName:asc' or 'fieldName:desc'\n if (typeof sort === 'string') {\n const [field, direction] = sort.split(':');\n if (field) {\n return {\n [field]: direction?.toLowerCase() === 'asc' ? 1 : -1,\n };\n }\n }\n\n // Handle array of sort specifications\n if (Array.isArray(sort)) {\n return sort.reduce((acc, sortItem) => {\n if (isObject(sortItem) && sortItem.key) {\n acc[sortItem.key] = sortItem.value?.toLowerCase() === 'asc' ? 1 : -1;\n }\n return acc;\n }, {});\n }\n\n // Fallback to default sort\n return { createdAt: -1 };\n }\n\n /**\n * Prepares an aggregation pipeline with standard stages\n * @param options Query options including filtering, sorting, pagination\n * @param customPipeline Optional custom pipeline stages to include\n * @returns Complete MongoDB aggregation pipeline\n */\n protected preparePipeline(options: GetAllArgs<SchemaType>, customPipeline: PipelineStage[] = []): PipelineStage[] {\n const { criteria, sort, limit, skip } = options;\n const pipeline: PipelineStage[] = [];\n\n // Match stage (filtering)\n if (criteria) {\n pipeline.push({\n $match: this.mapConditions(criteria),\n });\n }\n\n // Add custom pipeline stages\n if (customPipeline.length > 0) {\n pipeline.push(...customPipeline);\n }\n\n // Sort stage\n const sortBy = this.computeSort(sort);\n if (Object.keys(sortBy).length > 0) {\n pipeline.push({ $sort: sortBy });\n }\n\n // Pagination stages\n if (skip !== undefined) {\n pipeline.push({ $skip: skip || PAGINATION_OPTIONS.skip });\n }\n\n if (limit !== undefined) {\n pipeline.push({ $limit: limit || PAGINATION_OPTIONS.limit });\n }\n\n return pipeline;\n }\n\n /**\n * Execute an aggregation pipeline and transform the results\n */\n protected async aggregate(pipeline: PipelineStage[]): Promise<AsDomainType<SchemaType>[]> {\n try {\n const results = await this.model.aggregate(pipeline).exec();\n return this.transformDocuments(results);\n } catch (e) {\n this.logger.error(e, 'Error executing aggregation pipeline: %j', pipeline);\n throw e;\n }\n }\n\n public async count(conditions?: FilterQuery<SchemaType>): Promise<number> {\n return this.model.count(this.mapConditions(conditions)).exec();\n }\n\n public async get(\n conditions?: FilterQuery<SchemaType>,\n selectedFields?: string,\n ): Promise<AsDomainType<SchemaType> | null> {\n try {\n const response = await this.model.findOne(this.mapConditions(conditions), selectedFields).lean().exec();\n\n if (!response) return null;\n\n // Ensure id exists\n if (response && (response as any)._id && !(response as any).id) {\n (response as any).id = (response as any)._id.toString();\n }\n\n return response as AsDomainType<SchemaType>;\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', conditions);\n throw e;\n }\n }\n\n public async find(\n conditions: Partial<FilterQuery<SchemaType>>,\n selectedFields?: string,\n ): Promise<AsDomainType<SchemaType> | null> {\n try {\n const response = await this.model.findOne(conditions, selectedFields).lean().exec();\n\n if (!response) return null;\n\n // Ensure id exists\n if (response && (response as any)._id && !(response as any).id) {\n (response as any).id = (response as any)._id.toString();\n }\n\n return response as AsDomainType<SchemaType>;\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', conditions);\n throw e;\n }\n }\n\n public async getAll(options: GetAllArgs<SchemaType>): Promise<AsDomainType<SchemaType>[]> {\n try {\n const { criteria, selectedFields, sort, limit, skip } = options;\n const mappedCriteria = this.mapConditions(criteria);\n const sortBy = this.computeSort(sort);\n\n const response = await this.model\n .find(mappedCriteria, selectedFields)\n .sort(sortBy as any)\n .limit(limit || PAGINATION_OPTIONS.limit)\n .skip(skip || PAGINATION_OPTIONS.skip)\n .lean()\n .exec();\n\n // Ensure id exists for each document\n return response.map((doc) => {\n if (doc._id && !doc.id) {\n doc.id = doc._id.toString();\n }\n return doc as AsDomainType<SchemaType>;\n });\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', options);\n throw e;\n }\n }\n\n /**\n * Get all documents using aggregation pipeline\n */\n public async getAllWithPipeline(\n options: GetAllArgs<SchemaType>,\n customPipeline: PipelineStage[] = [],\n ): Promise<AsDomainType<SchemaType>[]> {\n try {\n const pipeline = this.preparePipeline(options, customPipeline);\n return this.aggregate(pipeline);\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with pipeline [%j]', customPipeline);\n throw e;\n }\n }\n\n public async getAllWithCount(options: GetAllArgs<SchemaType>): Promise<{\n data: AsDomainType<SchemaType>[];\n totalCount: number;\n }> {\n const data = await this.getAll(options);\n const totalCount = await this.count(options.criteria);\n return { totalCount, data };\n }\n\n /**\n * Get all documents with count using aggregation pipeline\n */\n public async getAllWithCountAndPipeline(\n options: GetAllArgs<SchemaType>,\n customPipeline: PipelineStage[] = [],\n ): Promise<{\n data: AsDomainType<SchemaType>[];\n totalCount: number;\n }> {\n // Clone options to avoid modifying the original\n const countOptions = { ...options };\n\n // Remove pagination for count\n delete countOptions.limit;\n delete countOptions.skip;\n\n // Prepare count pipeline (without pagination)\n const countPipeline = this.preparePipeline(countOptions, customPipeline);\n countPipeline.push({ $count: 'total' });\n\n // Execute both queries in parallel\n const [data, countResult] = await Promise.all([\n this.getAllWithPipeline(options, customPipeline),\n this.model.aggregate(countPipeline).exec(),\n ]);\n\n const totalCount = countResult?.[0]?.total || 0;\n return { data, totalCount };\n }\n\n public async create<T = CreateType<SchemaType>>(data: T): Promise<AsDomainType<SchemaType>> {\n try {\n // Handle custom _id if provided in the data\n const createData = { ...data } as any;\n\n // If id is provided but _id is not, map id to _id\n if (createData.id && !createData._id) {\n createData._id = Types.ObjectId.isValid(createData.id)\n ? new Types.ObjectId(createData.id)\n : createData.id;\n delete createData.id; // Remove id to avoid conflicts\n }\n\n const response = await this.model.create(createData);\n return this.transformDocument(response);\n } catch (e) {\n this.logger.error(e, 'Unable to create Model with data [%j]', data);\n throw e;\n }\n }\n\n public async bulkCreate<T = CreateType<SchemaType>>(data: T[]): Promise<AsDomainType<SchemaType>[]> {\n try {\n const response = await this.model.insertMany(data, {\n lean: true,\n ordered: true,\n });\n\n // Ensure id exists for each document\n return response.map((doc: any) => {\n if (doc._id && !doc.id) {\n doc.id = doc._id.toString();\n }\n return doc as AsDomainType<SchemaType>;\n });\n } catch (e) {\n this.logger.error(e, 'Unable to bulk create due to error [%s]', e.message);\n throw e;\n }\n }\n\n public async upsert<T = UpdateType<SchemaType>>(\n conditions: FilterQuery<SchemaType>,\n update: T,\n options: Record<string, unknown> = {},\n ): Promise<AsDomainType<SchemaType>> {\n return this.update(conditions, update, {\n upsert: true,\n ...options,\n });\n }\n\n public async update<T = UpdateType<SchemaType>>(\n criteria: FilterQuery<SchemaType>,\n update: T | UpdateQuery<SchemaType>,\n options: Record<string, unknown> = {},\n ): Promise<AsDomainType<SchemaType>> {\n try {\n const mappedCriteria = this.mapConditions(criteria);\n const mergedOptions = {\n new: true,\n useFindAndModify: false,\n ...options,\n };\n\n const { id } = criteria as any;\n let response;\n\n if (id) {\n response = await this.model.findByIdAndUpdate(id, update as any, mergedOptions).exec();\n } else {\n response = await this.model.findOneAndUpdate(mappedCriteria, update as any, mergedOptions).exec();\n }\n\n return this.transformDocument(response);\n } catch (e) {\n this.logger.error(e, 'Unable to Update with criteria [%j] and data [%j]', criteria, update);\n throw e;\n }\n }\n\n public async bulkUpdate<T = UpdateType<SchemaType>>(\n criteria: FilterQuery<SchemaType>,\n update: T | UpdateQuery<SchemaType>,\n options: Record<string, unknown> = {},\n ): Promise<AsDomainType<SchemaType>[]> {\n try {\n const mappedCriteria = this.mapConditions(criteria);\n await this.model.updateMany(mappedCriteria, update as any, options);\n\n // Fetch the updated documents\n const response = await this.model.find(mappedCriteria).lean().exec();\n\n // Ensure id exists for each document\n return response.map((doc) => {\n if (doc._id && !doc.id) {\n doc.id = doc._id.toString();\n }\n return doc as AsDomainType<SchemaType>;\n });\n } catch (e) {\n this.logger.error(e, 'Unable to Bulk Update with criteria [%j] and data [%j]', criteria, update);\n throw e;\n }\n }\n\n public async delete(criteria: FilterQuery<SchemaType>): Promise<boolean> {\n try {\n const mappedCriteria = this.mapConditions(criteria);\n let deleted;\n\n if (criteria?.id) {\n deleted = await this.model.findByIdAndDelete(criteria.id);\n } else {\n deleted = await this.model.findOneAndDelete(mappedCriteria);\n }\n\n return !!deleted;\n } catch (e) {\n this.logger.error(e, 'Unable to delete the model with criteria [%j]', criteria);\n throw e;\n }\n }\n\n public async bulkDelete(criteria: FilterQuery<SchemaType>): Promise<number> {\n try {\n const mappedCriteria = this.mapConditions(criteria);\n const deleted = await this.model.deleteMany(mappedCriteria);\n return deleted?.deletedCount || 0;\n } catch (e) {\n this.logger.error(e, 'Unable to delete the model with criteria [%j]', criteria);\n throw e;\n }\n }\n\n public async bulkGet(ids: string[], selectedFields?: string): Promise<AsDomainType<SchemaType>[]> {\n try {\n // Create a query that handles both ObjectId and string IDs\n const query: any = { _id: { $in: [] } };\n\n // Process each ID\n ids?.forEach((id) => {\n if (Types.ObjectId.isValid(id)) {\n query._id.$in.push(new Types.ObjectId(id));\n } else {\n query._id.$in.push(id); // Add as string\n }\n });\n\n let findQuery = this.model.find(query);\n\n // apply select if selectedFields is provided\n if (selectedFields) {\n findQuery = findQuery.select(selectedFields);\n }\n\n const results = await findQuery.lean().exec();\n\n // Ensure id exists for each document\n return results.map((doc) => {\n if ((doc as any)._id && !(doc as any).id) {\n (doc as any).id = (doc as any)._id.toString();\n }\n return doc as AsDomainType<SchemaType>;\n });\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', ids);\n throw e;\n }\n }\n}\n"],"names":[],"mappings":";;AAsBa,IAAA,mBAAmB,GAAzB,qBAAA,GAAA,MAAM,mBAAmB,CAAA;AAShB,IAAA,SAAA,CAAA;AARJ,IAAA,OAAO,CAAgB;AAErB,IAAA,MAAM,CAAoB;AAEpC,IAAA,KAAK,CAAqC;AAE1C,IAAA,WAAA,CAEY,SAAgD,EAExD,EAAc,EAEd,MAAyB,EAEzB,OAAuB,EAAA;QANf,IAAS,CAAA,SAAA,GAAT,SAAS,CAAuC;;QASxD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,qBAAqB,CAAC,EAAE,CAAuC,CAAC;AAClF,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACvB,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,qBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;KACvE;AAED;;;AAGG;AACK,IAAA,qBAAqB,CAAC,EAAc,EAAA;A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AAC;;AAG9C,YAAA,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,KAAI;gBACvB,IAAK,GAAW,CAAC,GAAG,IAAI,CAAE,GAAW,CAAC,EAAE,EAAE;oBACrC,GAAW,CAAC,EAAE,GAAI,GAAW,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;iBACjD;AACD,gBAAA,OAAO,GAA+B,CAAC;AAC3C,aAAC,CAAC,CAAC;SACN;QAAC,OAAO,CAAC,EAAE;YACR,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,6CAA6C,EAAE,GAAG,CAAC,CAAC;AACzE,YAAA,MAAM,CAAC,CAAC;SACX;KACJ;EACJ;AA9eY,mBAAmB,GAAA,qBAAA,GAAA,UAAA,CAAA;AAD/B,IAAA,UAAU,EAAE;IASJ,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;IAIX,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;IAEX,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;+CAHR,UAAU,EAAA,MAAA,EAAA,QAAA,EAAA,GAAA,OAIJ,aAAa,KAAA,WAAA,IAAb,aAAa,CAAA,KAAA,UAAA,GAAA,EAAA,GAAA,MAAA,CAAA,CAAA;AAflB,CAAA,EAAA,mBAAmB,CA8e/B"}
@@ -1,6 +1,7 @@
1
1
  import { CdmLogger } from '@cdm-logger/core';
2
2
  import { Connection, Document, FilterQuery, Model, PipelineStage, UpdateQuery } from 'mongoose';
3
- import { GetAllArgs, IBaseRepository, IMongoOptions } from '../../interfaces';
3
+ import { GetAllArgs, IMongoOptions } from '../../interfaces';
4
+ import { IBaseRepository } from 'src/interfaces/index.old';
4
5
  export declare class BaseRepository<T, D = Document<T>> implements IBaseRepository<T, D> {
5
6
  private modelFunc;
6
7
  private options;
@@ -1 +1 @@
1
- {"version":3,"file":"base-repository.js","sources":["../../../src/store/repositories/base-repository.ts"],"sourcesContent":["import { isObject } from 'lodash-es';\nimport { CdmLogger } from '@cdm-logger/core';\nimport { Connection, Document, FilterQuery, Model, PipelineStage, Types, UpdateQuery } from 'mongoose';\nimport { injectable, unmanaged } from 'inversify';\nimport { GetAllArgs, IBaseRepository, IMongoOptions, PAGINATION_OPTIONS } from '../../interfaces';\n\n@injectable()\nexport class BaseRepository<T, D = Document<T>> implements IBaseRepository<T, D> {\n private options: IMongoOptions;\n\n protected logger: CdmLogger.ILogger;\n\n model: Model<D>;\n\n constructor(\n @unmanaged()\n private modelFunc: (db: Connection) => Model<D>,\n @unmanaged()\n db: Connection,\n @unmanaged()\n logger: CdmLogger.ILogger,\n @unmanaged()\n options?: IMongoOptions,\n ) {\n this.model = modelFunc(db);\n this.options = options;\n this.logger = logger.child({ className: BaseRepository.name });\n }\n\n private computeSort(sort: GetAllArgs<D>['sort']): Record<string, 1 | -1> | null {\n if (isObject(sort)) {\n return { [sort?.key]: sort.value.toLowerCase() === 'asc' ? 1 : -1 };\n }\n return null;\n }\n\n preparePipeLine(options: GetAllArgs<D>): PipelineStage[] {\n const { criteria, selectedFields, sort, limit, skip } = options;\n // map id to mongoose _id\n const mappedCriteria = Object.entries(criteria || {}).reduce(\n (acc, [key, value]) => ({\n ...acc,\n [key]: Types.ObjectId.isValid(value) ? new Types.ObjectId(value) : value,\n }),\n { id: undefined },\n );\n const { id, ...rest } = mappedCriteria;\n const projectedFields = selectedFields?.split(' ').reduce(\n (acc, key) => ({\n ...acc,\n [key]: 1,\n }),\n {},\n );\n return [\n { $match: Object.assign({}, rest, id ? { _id: id } : {}) },\n ...(sort ? [{ $sort: this.computeSort(sort) }] : []),\n ...(selectedFields?.length\n ? [\n {\n $project: projectedFields,\n },\n ]\n : []),\n { $skip: skip || PAGINATION_OPTIONS.skip },\n { $limit: limit || PAGINATION_OPTIONS.limit },\n { $addFields: { id: '$_id' } },\n { $project: { _id: 0 } },\n ];\n }\n\n // public async getAll(options: GetAllArgs<D>): Promise<T[]> {\n // try {\n // return this.model.aggregate(this.preparePipeLine(options));\n // } catch (e) {\n // this.logger.error(e, 'Unable to retrieve Model with options ${JSON.stringify(options)}`);\n // throw e;\n // }\n // }\n\n public async getAll(options: GetAllArgs<D>): Promise<T[]> {\n try {\n const { criteria, selectedFields, sort, limit, skip } = options;\n // map id to mongoose _id\n const { id, ...rest } = criteria || { id: undefined };\n const sortBy = isObject(sort) ? { [sort?.key]: sort.value } : { createdAt: 1 };\n const response = await this.model\n .find({ ...rest, ...(id ? { _id: id } : {}) }, selectedFields)\n .sort(sortBy as never)\n .limit(limit || PAGINATION_OPTIONS.limit)\n .skip(skip || PAGINATION_OPTIONS.skip)\n .exec();\n return response.map((i) => i?.toObject()) as T[];\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', options);\n throw e;\n }\n }\n\n public async getAllWithCount(options: GetAllArgs<D>): Promise<{ data: T[]; totalCount: number }> {\n const data = await this.getAll(options);\n const totalCount = await this.count(options.criteria);\n return { totalCount, data };\n }\n\n // public async getAllWithCount(options: GetAllArgs<D>): Promise<{ data: T[], totalCount: number }> {\n // try {\n // const pipeline: PipelineStage[] = this.preparePipeLine(options);\n // pipeline.push({\n // $facet: {\n // data: [{\n // $group: {\n // _id: null,\n // items: { $push: '$$ROOT' }\n // }\n // }],\n // count: [{ $count: 'count' }],\n // },\n // })\n // const result = await this.model.aggregate(pipeline);\n // const data = result[0]?.data[0]?.items || [];\n // const totalCount = result[0]?.count[0]?.count || 0;\n // return { data, totalCount };\n // } catch (e) {\n // this.logger.error(e, 'Unable to retrieve Model with options ${JSON.stringify(options)}`);\n // throw e;\n // }\n // }\n\n // eslint-disable-next-line class-methods-use-this\n private mapConditions(conditions: FilterQuery<D>): FilterQuery<D> {\n const { id: _id, ...remaining } = conditions;\n return {\n ...(_id ? { _id } : {}),\n ...remaining,\n };\n }\n\n public async count(conditions?: FilterQuery<D>): Promise<number> {\n return this.model.count(conditions).exec();\n }\n\n public async get(conditions?: FilterQuery<D>, selectedFields?: string): Promise<T> {\n try {\n const response = await this.model.findOne(this.mapConditions(conditions), selectedFields).exec();\n return response?.toObject() as T;\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', conditions);\n throw e;\n }\n }\n\n public async bulkGet(ids: string[]): Promise<T[]> {\n try {\n const results = await this.model.find().setOptions({ batchSize: 100 }).where('_id').in(ids).exec();\n return results.map((i) => i.toObject()) as T[];\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', ids);\n throw e;\n }\n }\n\n public async find(conditions: Partial<FilterQuery<D>>, selectedFields?: string): Promise<T> {\n try {\n const response = await this.model.findOne(conditions, selectedFields).exec();\n return response?.toObject() as T;\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', conditions);\n throw e;\n }\n }\n\n public async create<I>(data: I): Promise<T> {\n try {\n const response = await this.model.create(data);\n return response.toObject() as T;\n } catch (e) {\n this.logger.error(\n e,\n 'Unable to create Model with data ${JSON.stringify(data)} due to error [%s]',\n e.message,\n );\n throw e;\n }\n }\n\n public async bulkCreate<I>(data: I[]): Promise<T[]> {\n try {\n const response = await this.model.insertMany(data, {\n lean: true,\n ordered: true,\n });\n return response as unknown as T[];\n } catch (e) {\n this.logger.error(e, 'Unable to bulk create due to error [%s]', e.message);\n }\n }\n\n public async upsert<I>(conditions: FilterQuery<D>, update: I, options?: Record<string, unknown>): Promise<T> {\n return this.update<I>(conditions, update, {\n upsert: true,\n ...options,\n });\n }\n\n public async bulkUpdate<I>(\n criteria: FilterQuery<D>,\n update: UpdateQuery<D>,\n options: Record<string, unknown>,\n ): Promise<T[]> {\n try {\n const { id, ...rest } = criteria;\n const processedCriteria = id ? { _id: id, ...rest } : criteria;\n const res = await this.model.updateMany(processedCriteria, update);\n if (res) {\n const response = await this.model.find(processedCriteria).exec();\n return response.map((i) => i?.toObject()) as T[];\n } else {\n this.logger.error('Unable to Bulk Update with criteria [%j] and data [%j]', criteria, update);\n throw new Error('Unable to do bulk update');\n }\n } catch (e) {\n this.logger.error(e, 'Unable to Bulk Update with criteria [%j] and data [%j]', criteria, update);\n throw e;\n }\n }\n\n public async update<I>(\n criteria: FilterQuery<D>,\n update: UpdateQuery<D>,\n options: Record<string, unknown>,\n ): Promise<T> {\n try {\n const { id, ...rest } = criteria;\n const processedCriteria = id ? { _id: id, ...rest } : criteria;\n const mergedOptions = {\n new: true,\n useFindAndModify: false,\n ...options,\n };\n if (id) {\n return (await this.model\n .findByIdAndUpdate(id, update as unknown as never, mergedOptions)\n .exec()) as unknown as Promise<T>;\n }\n return (await this.model\n .findOneAndUpdate(processedCriteria, update as unknown as never, mergedOptions)\n .exec()) as unknown as Promise<T>;\n } catch (e) {\n this.logger.error(e, 'Unable to Update with criteria [%j] and data [%j]', criteria, update);\n throw e;\n }\n }\n\n public async delete(criteria: FilterQuery<D>): Promise<boolean> {\n try {\n let deleted;\n if (criteria?.id) {\n deleted = await this.model.findByIdAndDelete(criteria.id);\n } else {\n deleted = await this.model.findOneAndDelete(this.mapConditions(criteria));\n }\n return !!deleted;\n } catch (e) {\n this.logger.error(e, 'Unable to delete the model with criteria [%j]', criteria);\n throw e;\n }\n }\n\n public async bulkDelete(criteria: FilterQuery<D>): Promise<number> {\n try {\n const deleted = await this.model.deleteMany(this.mapConditions(criteria));\n return deleted?.deletedCount || 0;\n } catch (e) {\n this.logger.error(e, 'Unable to delete the model with criteria [%j]', criteria);\n throw e;\n }\n }\n}\n"],"names":[],"mappings":";AAOa,IAAA,cAAc,GAApB,gBAAA,GAAA,MAAM,cAAc,CAAA;AASX,IAAA,SAAA,CAAA;AARJ,IAAA,OAAO,CAAgB;AAErB,IAAA,MAAM,CAAoB;AAEpC,IAAA,KAAK,CAAW;AAEhB,IAAA,WAAA,CAEY,SAAuC,EAE/C,EAAc,EAEd,MAAyB,EAEzB,OAAuB,EAAA;QANf,IAAS,CAAA,SAAA,GAAT,SAAS,CAA8B;AAQ/C,QAAA,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,EAAE,CAAC,CA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,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,+CAA+C,EAAE,QAAQ,CAAC,CAAC;AAChF,YAAA,MAAM,CAAC,CAAC;SACX;KACJ;EACJ;AA/QY,cAAc,GAAA,gBAAA,GAAA,UAAA,CAAA;AAD1B,IAAA,UAAU,EAAE;IASJ,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;IAEX,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;IAEX,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;IAEX,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;+CAHR,UAAU,EAAA,MAAA,EAAA,MAAA,CAAA,CAAA;AAXT,CAAA,EAAA,cAAc,CA+Q1B"}
1
+ {"version":3,"file":"base-repository.js","sources":["../../../src/store/repositories/base-repository.ts"],"sourcesContent":["import { isObject } from 'lodash-es';\nimport { CdmLogger } from '@cdm-logger/core';\nimport { Connection, Document, FilterQuery, Model, PipelineStage, Types, UpdateQuery } from 'mongoose';\nimport { injectable, unmanaged } from 'inversify';\nimport { GetAllArgs, IMongoOptions, PAGINATION_OPTIONS } from '../../interfaces';\nimport { IBaseRepository } from 'src/interfaces/index.old';\n\n@injectable()\nexport class BaseRepository<T, D = Document<T>> implements IBaseRepository<T, D> {\n private options: IMongoOptions;\n\n protected logger: CdmLogger.ILogger;\n\n model: Model<D>;\n\n constructor(\n @unmanaged()\n private modelFunc: (db: Connection) => Model<D>,\n @unmanaged()\n db: Connection,\n @unmanaged()\n logger: CdmLogger.ILogger,\n @unmanaged()\n options?: IMongoOptions,\n ) {\n this.model = modelFunc(db);\n this.options = options;\n this.logger = logger.child({ className: BaseRepository.name });\n }\n\n private computeSort(sort: GetAllArgs<D>['sort']): Record<string, 1 | -1> | null {\n if (isObject(sort)) {\n return { [sort?.key]: sort.value.toLowerCase() === 'asc' ? 1 : -1 };\n }\n return null;\n }\n\n preparePipeLine(options: GetAllArgs<D>): PipelineStage[] {\n const { criteria, selectedFields, sort, limit, skip } = options;\n // map id to mongoose _id\n const mappedCriteria = Object.entries(criteria || {}).reduce(\n (acc, [key, value]) => ({\n ...acc,\n [key]: Types.ObjectId.isValid(value) ? new Types.ObjectId(value) : value,\n }),\n { id: undefined },\n );\n const { id, ...rest } = mappedCriteria;\n const projectedFields = selectedFields?.split(' ').reduce(\n (acc, key) => ({\n ...acc,\n [key]: 1,\n }),\n {},\n );\n return [\n { $match: Object.assign({}, rest, id ? { _id: id } : {}) },\n ...(sort ? [{ $sort: this.computeSort(sort) }] : []),\n ...(selectedFields?.length\n ? [\n {\n $project: projectedFields,\n },\n ]\n : []),\n { $skip: skip || PAGINATION_OPTIONS.skip },\n { $limit: limit || PAGINATION_OPTIONS.limit },\n { $addFields: { id: '$_id' } },\n { $project: { _id: 0 } },\n ];\n }\n\n // public async getAll(options: GetAllArgs<D>): Promise<T[]> {\n // try {\n // return this.model.aggregate(this.preparePipeLine(options));\n // } catch (e) {\n // this.logger.error(e, 'Unable to retrieve Model with options ${JSON.stringify(options)}`);\n // throw e;\n // }\n // }\n\n public async getAll(options: GetAllArgs<D>): Promise<T[]> {\n try {\n const { criteria, selectedFields, sort, limit, skip } = options;\n // map id to mongoose _id\n const { id, ...rest } = criteria || { id: undefined };\n const sortBy = isObject(sort) ? { [sort?.key]: sort.value } : { createdAt: 1 };\n const response = await this.model\n .find({ ...rest, ...(id ? { _id: id } : {}) }, selectedFields)\n .sort(sortBy as never)\n .limit(limit || PAGINATION_OPTIONS.limit)\n .skip(skip || PAGINATION_OPTIONS.skip)\n .exec();\n return response.map((i) => i?.toObject()) as T[];\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', options);\n throw e;\n }\n }\n\n public async getAllWithCount(options: GetAllArgs<D>): Promise<{ data: T[]; totalCount: number }> {\n const data = await this.getAll(options);\n const totalCount = await this.count(options.criteria);\n return { totalCount, data };\n }\n\n // public async getAllWithCount(options: GetAllArgs<D>): Promise<{ data: T[], totalCount: number }> {\n // try {\n // const pipeline: PipelineStage[] = this.preparePipeLine(options);\n // pipeline.push({\n // $facet: {\n // data: [{\n // $group: {\n // _id: null,\n // items: { $push: '$$ROOT' }\n // }\n // }],\n // count: [{ $count: 'count' }],\n // },\n // })\n // const result = await this.model.aggregate(pipeline);\n // const data = result[0]?.data[0]?.items || [];\n // const totalCount = result[0]?.count[0]?.count || 0;\n // return { data, totalCount };\n // } catch (e) {\n // this.logger.error(e, 'Unable to retrieve Model with options ${JSON.stringify(options)}`);\n // throw e;\n // }\n // }\n\n // eslint-disable-next-line class-methods-use-this\n private mapConditions(conditions: FilterQuery<D>): FilterQuery<D> {\n const { id: _id, ...remaining } = conditions;\n return {\n ...(_id ? { _id } : {}),\n ...remaining,\n };\n }\n\n public async count(conditions?: FilterQuery<D>): Promise<number> {\n return this.model.count(conditions).exec();\n }\n\n public async get(conditions?: FilterQuery<D>, selectedFields?: string): Promise<T> {\n try {\n const response = await this.model.findOne(this.mapConditions(conditions), selectedFields).exec();\n return response?.toObject() as T;\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', conditions);\n throw e;\n }\n }\n\n public async bulkGet(ids: string[]): Promise<T[]> {\n try {\n const results = await this.model.find().setOptions({ batchSize: 100 }).where('_id').in(ids).exec();\n return results.map((i) => i.toObject()) as T[];\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', ids);\n throw e;\n }\n }\n\n public async find(conditions: Partial<FilterQuery<D>>, selectedFields?: string): Promise<T> {\n try {\n const response = await this.model.findOne(conditions, selectedFields).exec();\n return response?.toObject() as T;\n } catch (e) {\n this.logger.error(e, 'Unable to retrieve Model with criteria [%j]', conditions);\n throw e;\n }\n }\n\n public async create<I>(data: I): Promise<T> {\n try {\n const response = await this.model.create(data);\n return response.toObject() as T;\n } catch (e) {\n this.logger.error(\n e,\n 'Unable to create Model with data ${JSON.stringify(data)} due to error [%s]',\n e.message,\n );\n throw e;\n }\n }\n\n public async bulkCreate<I>(data: I[]): Promise<T[]> {\n try {\n const response = await this.model.insertMany(data, {\n lean: true,\n ordered: true,\n });\n return response as unknown as T[];\n } catch (e) {\n this.logger.error(e, 'Unable to bulk create due to error [%s]', e.message);\n }\n }\n\n public async upsert<I>(conditions: FilterQuery<D>, update: I, options?: Record<string, unknown>): Promise<T> {\n return this.update<I>(conditions, update, {\n upsert: true,\n ...options,\n });\n }\n\n public async bulkUpdate<I>(\n criteria: FilterQuery<D>,\n update: UpdateQuery<D>,\n options: Record<string, unknown>,\n ): Promise<T[]> {\n try {\n const { id, ...rest } = criteria;\n const processedCriteria = id ? { _id: id, ...rest } : criteria;\n const res = await this.model.updateMany(processedCriteria, update);\n if (res) {\n const response = await this.model.find(processedCriteria).exec();\n return response.map((i) => i?.toObject()) as T[];\n } else {\n this.logger.error('Unable to Bulk Update with criteria [%j] and data [%j]', criteria, update);\n throw new Error('Unable to do bulk update');\n }\n } catch (e) {\n this.logger.error(e, 'Unable to Bulk Update with criteria [%j] and data [%j]', criteria, update);\n throw e;\n }\n }\n\n public async update<I>(\n criteria: FilterQuery<D>,\n update: UpdateQuery<D>,\n options: Record<string, unknown>,\n ): Promise<T> {\n try {\n const { id, ...rest } = criteria;\n const processedCriteria = id ? { _id: id, ...rest } : criteria;\n const mergedOptions = {\n new: true,\n useFindAndModify: false,\n ...options,\n };\n if (id) {\n return (await this.model\n .findByIdAndUpdate(id, update as unknown as never, mergedOptions)\n .exec()) as unknown as Promise<T>;\n }\n return (await this.model\n .findOneAndUpdate(processedCriteria, update as unknown as never, mergedOptions)\n .exec()) as unknown as Promise<T>;\n } catch (e) {\n this.logger.error(e, 'Unable to Update with criteria [%j] and data [%j]', criteria, update);\n throw e;\n }\n }\n\n public async delete(criteria: FilterQuery<D>): Promise<boolean> {\n try {\n let deleted;\n if (criteria?.id) {\n deleted = await this.model.findByIdAndDelete(criteria.id);\n } else {\n deleted = await this.model.findOneAndDelete(this.mapConditions(criteria));\n }\n return !!deleted;\n } catch (e) {\n this.logger.error(e, 'Unable to delete the model with criteria [%j]', criteria);\n throw e;\n }\n }\n\n public async bulkDelete(criteria: FilterQuery<D>): Promise<number> {\n try {\n const deleted = await this.model.deleteMany(this.mapConditions(criteria));\n return deleted?.deletedCount || 0;\n } catch (e) {\n this.logger.error(e, 'Unable to delete the model with criteria [%j]', criteria);\n throw e;\n }\n }\n}\n"],"names":[],"mappings":";AAQa,IAAA,cAAc,GAApB,gBAAA,GAAA,MAAM,cAAc,CAAA;AASX,IAAA,SAAA,CAAA;AARJ,IAAA,OAAO,CAAgB;AAErB,IAAA,MAAM,CAAoB;AAEpC,IAAA,KAAK,CAAW;AAEhB,IAAA,WAAA,CAEY,SAAuC,EAE/C,EAAc,EAEd,MAAyB,EAEzB,OAAuB,EAAA;QANf,IAAS,CAAA,SAAA,GAAT,SAAS,CAA8B;AAQ/C,QAAA,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,EAAE,CAAC,CAAC;AAC3B,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACvB,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,gBAAc,CAAC,IAAI,EAAE,CAAC,CAAC;KAClE;AAEO,IAAA,WAAW,CAAC,IAA2B,EAAA;AAC3C,QAAA,IAAI,QAAQ,CAAC,IAAI,CAAC,EAAE;YAChB,OAAO,EAAE,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,KAAK,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;SACvE;AACD,QAAA,OAAO,IAAI,CAAC;KACf;AAED,IAAA,eAAe,CAAC,OAAsB,EAAA;AAClC,QAAA,MAAM,EAAE,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;;QAEhE,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAC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OAAO,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC;aAC7E;YACD,OAAO,CAAC,CAAC,OAAO,CAAC;SACpB;QAAC,OAAO,CAAC,EAAE;YACR,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,+CAA+C,EAAE,QAAQ,CAAC,CAAC;AAChF,YAAA,MAAM,CAAC,CAAC;SACX;KACJ;IAEM,MAAM,UAAU,CAAC,QAAwB,EAAA;AAC5C,QAAA,IAAI;AACA,YAAA,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC;AAC1E,YAAA,OAAO,OAAO,EAAE,YAAY,IAAI,CAAC,CAAC;SACrC;QAAC,OAAO,CAAC,EAAE;YACR,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,+CAA+C,EAAE,QAAQ,CAAC,CAAC;AAChF,YAAA,MAAM,CAAC,CAAC;SACX;KACJ;EACJ;AA/QY,cAAc,GAAA,gBAAA,GAAA,UAAA,CAAA;AAD1B,IAAA,UAAU,EAAE;IASJ,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;IAEX,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;IAEX,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;IAEX,OAAA,CAAA,CAAA,EAAA,SAAS,EAAE,CAAA;+CAHR,UAAU,EAAA,MAAA,EAAA,MAAA,CAAA,CAAA;AAXT,CAAA,EAAA,cAAc,CA+Q1B"}
@@ -2,4 +2,6 @@ export const SERVER_TYPES = {
2
2
  BaseMongoRepository: Symbol.for('BaseMongoRepository'),
3
3
  BaseMongoService: Symbol.for('BaseMongoService'),
4
4
  BaseService: Symbol.for('BaseService'),
5
- }
5
+ MongoDBMigration: Symbol.for('MongodbMigration'),
6
+ MongoDBConnection: Symbol.for('MongoDBConnection'),
7
+ };
@@ -28,9 +28,9 @@ import { AsDomainType, CreateType, GetAllArgs, GetAllWithCountResult, UpdateType
28
28
  export interface IBaseMongoRepository<SchemaType> {
29
29
  /**
30
30
  * The Mongoose model associated with this repository
31
- * Used for direct database operations
31
+ * SchemaType & { id: string } represents the schema with virtual id field included
32
32
  */
33
- model: Model<SchemaType>;
33
+ model: Model<SchemaType & { id: string }>;
34
34
 
35
35
  /**
36
36
  * Counts documents matching the specified conditions
@@ -26,7 +26,7 @@
26
26
 
27
27
  import { GetAllArgs, AsDomainType, CreateType, UpdateType, FilterCriteria } from './dbCommonTypes';
28
28
 
29
- export interface IBaseService<SchemaType> {
29
+ export interface IBaseService<SchemaType, CreateInterface = CreateType<SchemaType>, UpdateInterface = UpdateType<SchemaType>> {
30
30
  /**
31
31
  * Retrieves documents with pagination and total count
32
32
  * Useful for implementing paginated UIs that need to know total pages
@@ -131,7 +131,7 @@ export interface IBaseService<SchemaType> {
131
131
  * role: 'user'
132
132
  * });
133
133
  */
134
- create<T = CreateType<SchemaType>>(data: T): Promise<AsDomainType<SchemaType>>;
134
+ create(data: CreateInterface): Promise<AsDomainType<SchemaType>>;
135
135
 
136
136
  /**
137
137
  * Creates multiple documents in a single operation
@@ -146,7 +146,7 @@ export interface IBaseService<SchemaType> {
146
146
  * { name: 'Jane', email: 'jane@example.com' }
147
147
  * ]);
148
148
  */
149
- bulkCreate<T = CreateType<SchemaType>>(data: T[]): Promise<AsDomainType<SchemaType>[]>;
149
+ bulkCreate(data: CreateInterface[]): Promise<AsDomainType<SchemaType>[]>;
150
150
 
151
151
  /**
152
152
  * Updates a document by ID
@@ -170,7 +170,7 @@ export interface IBaseService<SchemaType> {
170
170
  * true
171
171
  * );
172
172
  */
173
- update<T = UpdateType<SchemaType>>(id: string, data: T, overwrite?: boolean): Promise<AsDomainType<SchemaType>>;
173
+ update(id: string, data: Partial<UpdateInterface>, overwrite?: boolean): Promise<AsDomainType<SchemaType>>;
174
174
 
175
175
  /**
176
176
  * Creates a new document or updates it if ID is provided
@@ -194,8 +194,8 @@ export interface IBaseService<SchemaType> {
194
194
  * price: 129.99
195
195
  * });
196
196
  */
197
- insert<T = CreateType<SchemaType>>(
198
- data: T & { id?: string },
197
+ insert(
198
+ data: (CreateInterface | UpdateInterface) & { id?: string },
199
199
  overwrite?: boolean,
200
200
  ): Promise<AsDomainType<SchemaType>>;
201
201
 
@@ -36,7 +36,7 @@
36
36
  import type { ServiceBroker, ServiceSchema } from 'moleculer';
37
37
  import { BaseServiceCommands } from 'common';
38
38
  import { IBaseService } from './IBaseService';
39
-
39
+ import { CreateType, UpdateType } from './dbCommonTypes';
40
40
 
41
41
  /**
42
42
  * Interface for the BaseServiceMixin function
@@ -76,8 +76,8 @@ import { IBaseService } from './IBaseService';
76
76
  * };
77
77
  */
78
78
  export interface IBaseServiceMixinFunction {
79
- <T>(
80
- service: IBaseService<T>,
79
+ <T, C = CreateType<T>, U = UpdateType<T>>(
80
+ service: IBaseService<T, C, U>,
81
81
  broker?: ServiceBroker,
82
82
  name?: string,
83
83
  events?: BaseServiceCommands[],
@@ -114,6 +114,23 @@ export interface IBaseServiceMixinActions {
114
114
  };
115
115
  };
116
116
 
117
+ /**
118
+ * Get multiple documents by their IDs
119
+ *
120
+ * This action retrieves multiple entities by their unique identifiers.
121
+ * It maps to the IBaseService.getByIds method and handles parameter validation.
122
+ * Useful for retrieving a specific set of entities in a single operation.
123
+ */
124
+ [BaseServiceCommands.GetByIds]: {
125
+ params: {
126
+ ids: {
127
+ type: 'array',
128
+ items: 'string',
129
+ optional: false
130
+ };
131
+ };
132
+ };
133
+
117
134
  /**
118
135
  * Count documents matching criteria
119
136
  *
@@ -20,6 +20,7 @@
20
20
  * @see IBaseMongoRepository - MongoDB repository implementation using these types
21
21
  */
22
22
  import { ISort } from 'common';
23
+ import type { ObjectId } from 'mongodb';
23
24
  /**
24
25
  * Generic filter type that doesn't depend on specific database implementation
25
26
  * Can be used for any database query operations
@@ -82,7 +83,7 @@ export interface GetAllArgs<T> {
82
83
  * // email: string;
83
84
  * // }
84
85
  */
85
- export type AsDomainType<T> = Omit<T, '_id'> & { id: string };
86
+ export type AsDomainType<SchemaType> = Omit<SchemaType, '_id'> & { _id?: ObjectId } & { id: string };
86
87
 
87
88
  /**
88
89
  * Type for paginated results that include both data and total count
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@common-stack/store-mongo",
3
- "version": "7.1.1-alpha.9",
3
+ "version": "7.2.1-alpha.3",
4
4
  "description": "Sample core for higher packages to depend on",
5
5
  "license": "ISC",
6
6
  "author": "CDMBase LLC",
@@ -24,10 +24,10 @@
24
24
  "watch": "npm run build:lib:watch"
25
25
  },
26
26
  "dependencies": {
27
- "@common-stack/core": "7.0.4-alpha.17"
27
+ "@common-stack/core": "7.1.1-alpha.63"
28
28
  },
29
29
  "devDependencies": {
30
- "common": "7.1.1-alpha.8",
30
+ "common": "7.1.1-alpha.49",
31
31
  "moleculer": "^0.14.33",
32
32
  "mongoose": "^6.12.8"
33
33
  },
@@ -48,7 +48,7 @@
48
48
  "./${libDir}/templates/repositories/IBaseMongoRepository.ts.template",
49
49
  "./${libDir}/templates/repositories/IBaseService.ts.template",
50
50
  "./${libDir}/templates/repositories/IBaseServiceMixin.ts.template",
51
- "./${libDir}/templates/repositories/IDataLoader.ts.template",
51
+ "./${libDir}/templates/repositories/DataLoader.ts.template",
52
52
  "./${libDir}/templates/repositories/mongoCommonTypes.ts.template",
53
53
  "./${libDir}/templates/repositories/dbCommonTypes.ts.template",
54
54
  "./${libDir}/templates/repositories/DatabaseMigration.ts.template"
@@ -58,5 +58,5 @@
58
58
  "typescript": {
59
59
  "definition": "lib/index.d.ts"
60
60
  },
61
- "gitHead": "54c1746625cac7261ce4df690ae05104064a0e88"
61
+ "gitHead": "fa05313b4ec3db2667673fd53c59fd75d913f2f1"
62
62
  }