@common-stack/store-mongo 8.0.2-alpha.0 → 8.1.1-alpha.13

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 (77) hide show
  1. package/LICENSE +34 -21
  2. package/lib/containers/container.d.ts +14 -0
  3. package/lib/containers/container.js +17 -0
  4. package/lib/containers/container.js.map +1 -0
  5. package/lib/containers/index.d.ts +1 -0
  6. package/lib/dataloaders/bulk-dataloader-v2.d.ts +40 -0
  7. package/lib/dataloaders/bulk-dataloader-v2.js +118 -0
  8. package/lib/dataloaders/bulk-dataloader-v2.js.map +1 -0
  9. package/lib/dataloaders/bulk-dataloader-v2.test.d.ts +1 -0
  10. package/lib/dataloaders/bulk-dataloader.d.ts +1 -1
  11. package/lib/dataloaders/bulk-dataloader.js.map +1 -1
  12. package/lib/dataloaders/bulk-dataloader.test.d.ts +1 -0
  13. package/lib/dataloaders/index.d.ts +1 -0
  14. package/lib/graphql/schema/base-services.graphql +238 -0
  15. package/lib/helpers/mongoose-connection.js.map +1 -1
  16. package/lib/index.d.ts +2 -1
  17. package/lib/index.js +1 -1
  18. package/lib/interfaces/base-repository.d.ts +1 -5
  19. package/lib/interfaces/base-service.d.ts +1 -1
  20. package/lib/interfaces/getAllArgs.d.ts +135 -0
  21. package/lib/interfaces/getAllArgs.js +39 -0
  22. package/lib/interfaces/getAllArgs.js.map +1 -0
  23. package/lib/interfaces/index.d.ts +1 -4
  24. package/lib/interfaces/index.old.d.ts +3 -0
  25. package/lib/mixins/BaseServiceMixin.d.ts +45 -0
  26. package/lib/mixins/BaseServiceMixin.js +212 -0
  27. package/lib/mixins/BaseServiceMixin.js.map +1 -0
  28. package/lib/mixins/__tests__/BaseServiceMixin.test.d.ts +1 -0
  29. package/lib/mixins/base-service-mixin.js.map +1 -1
  30. package/lib/mixins/index.d.ts +1 -0
  31. package/lib/module.d.ts +2 -0
  32. package/lib/module.js +4 -0
  33. package/lib/module.js.map +1 -0
  34. package/lib/services/BaseProxyService.d.ts +28 -0
  35. package/lib/services/BaseProxyService.js +52 -0
  36. package/lib/services/BaseProxyService.js.map +1 -0
  37. package/lib/services/BaseService.d.ts +23 -0
  38. package/lib/services/BaseService.js +65 -0
  39. package/lib/services/BaseService.js.map +1 -0
  40. package/lib/services/BaseService.test.d.ts +1 -0
  41. package/lib/services/ConnectionPoolManager.d.ts +54 -0
  42. package/lib/services/ConnectionPoolManager.js +163 -0
  43. package/lib/services/ConnectionPoolManager.js.map +1 -0
  44. package/lib/services/base-proxy-service.d.ts +2 -1
  45. package/lib/services/base-proxy-service.js.map +1 -1
  46. package/lib/services/base-service.d.ts +2 -1
  47. package/lib/services/base-service.js.map +1 -1
  48. package/lib/services/index.d.ts +3 -0
  49. package/lib/store/models/common-options-v2.d.ts +16 -0
  50. package/lib/store/models/common-options-v2.js +40 -0
  51. package/lib/store/models/common-options-v2.js.map +1 -0
  52. package/lib/store/models/common-options.js.map +1 -1
  53. package/lib/store/models/index.d.ts +1 -0
  54. package/lib/store/repositories/BaseMongoRepository.d.ts +72 -0
  55. package/lib/store/repositories/BaseMongoRepository.js +423 -0
  56. package/lib/store/repositories/BaseMongoRepository.js.map +1 -0
  57. package/lib/store/repositories/BaseMongoRepository.test.d.ts +1 -0
  58. package/lib/store/repositories/CustomIdRepository.test.d.ts +1 -0
  59. package/lib/store/repositories/base-repository.d.ts +2 -1
  60. package/lib/store/repositories/base-repository.js +1 -1
  61. package/lib/store/repositories/base-repository.js.map +1 -1
  62. package/lib/store/repositories/index.d.ts +1 -0
  63. package/lib/templates/constants/SERVER_TYPES.ts.template +7 -0
  64. package/lib/templates/repositories/DataLoader.ts.template +211 -0
  65. package/lib/templates/repositories/DatabaseMigration.ts.template +13 -0
  66. package/lib/templates/repositories/IBaseMongoRepository.ts.template +284 -0
  67. package/lib/templates/repositories/IBaseService.ts.template +231 -0
  68. package/lib/templates/repositories/IBaseServiceMixin.ts.template +477 -0
  69. package/lib/templates/repositories/dbCommonTypes.ts.template +140 -0
  70. package/lib/templates/repositories/moleculerEventHandler.ts.template.toberemoved +118 -0
  71. package/lib/templates/repositories/mongoCommonTypes.ts.template +21 -0
  72. package/lib/templates/repositories/typedMoleculerService.ts.template.toberemoved +1188 -0
  73. package/lib/templates/repositories/zodToMoleculer.ts.template.toberemoved +133 -0
  74. package/package.json +22 -5
  75. package/lib/interfaces/base-repository.js +0 -5
  76. package/lib/interfaces/base-repository.js.map +0 -1
  77. package/lib/interfaces/get-all-args.d.ts +0 -9
@@ -0,0 +1,23 @@
1
+ import { FilterQuery } from 'mongoose';
2
+ import { GetAllArgs, IBaseMongoRepository, IBaseService, AsDomainType, CreateType, UpdateType } from 'common/server';
3
+ export declare class BaseService2<SchemaType, C = CreateType<SchemaType>, U = UpdateType<SchemaType>> implements IBaseService<SchemaType, C, U> {
4
+ protected repository: IBaseMongoRepository<SchemaType>;
5
+ constructor(repository: IBaseMongoRepository<SchemaType>);
6
+ getAllWithCount(options: GetAllArgs<SchemaType>): Promise<{
7
+ data: AsDomainType<SchemaType>[];
8
+ totalCount: number;
9
+ }>;
10
+ count(conditions?: FilterQuery<SchemaType>): Promise<number>;
11
+ get(conditions: string | FilterQuery<SchemaType>): Promise<AsDomainType<SchemaType> | null>;
12
+ getByName(name: string): Promise<AsDomainType<SchemaType> | null>;
13
+ getAll(options: GetAllArgs<SchemaType>): Promise<AsDomainType<SchemaType>[]>;
14
+ getByIds(ids: string[]): Promise<AsDomainType<SchemaType>[]>;
15
+ create<T = CreateType<SchemaType>>(data: T): Promise<AsDomainType<SchemaType>>;
16
+ bulkCreate<T = CreateType<SchemaType>>(data: T[]): Promise<AsDomainType<SchemaType>[]>;
17
+ update<T = UpdateType<SchemaType>>(id: string, data: T, overwrite?: boolean): Promise<AsDomainType<SchemaType>>;
18
+ insert<T = CreateType<SchemaType>>(data: T & {
19
+ id?: string;
20
+ }, overwrite?: boolean): Promise<AsDomainType<SchemaType>>;
21
+ delete(id: string | FilterQuery<SchemaType>): Promise<boolean>;
22
+ bulkDelete(criteria: FilterQuery<SchemaType>): Promise<number>;
23
+ }
@@ -0,0 +1,65 @@
1
+ import {__decorate,__metadata}from'tslib';import {injectable}from'inversify';import {IBaseMongoRepository}from'common/server';var _a;
2
+ let BaseService2 = class BaseService2 {
3
+ repository;
4
+ constructor(repository) {
5
+ this.repository = repository;
6
+ }
7
+ async getAllWithCount(options) {
8
+ return this.repository.getAllWithCount(options);
9
+ }
10
+ count(conditions) {
11
+ return this.repository.count(conditions);
12
+ }
13
+ get(conditions) {
14
+ if (typeof conditions === 'string') {
15
+ return this.repository.get({ id: conditions });
16
+ }
17
+ return this.repository.get(conditions);
18
+ }
19
+ getByName(name) {
20
+ return this.repository.get({ name });
21
+ }
22
+ getAll(options) {
23
+ return this.repository.getAll(options);
24
+ }
25
+ getByIds(ids) {
26
+ return this.repository.bulkGet(ids);
27
+ }
28
+ create(data) {
29
+ return this.repository.create(data);
30
+ }
31
+ bulkCreate(data) {
32
+ return this.repository.bulkCreate(data);
33
+ }
34
+ async update(id, data, overwrite = false) {
35
+ return this.repository.update({ id }, data, { overwrite });
36
+ }
37
+ async insert(data, overwrite = true) {
38
+ const { id, ...rest } = data;
39
+ if (id) {
40
+ try {
41
+ const existing = await this.repository.get({ id });
42
+ if (existing) {
43
+ return this.update(id, rest, overwrite);
44
+ }
45
+ }
46
+ catch (error) {
47
+ // If not found, continue to create
48
+ }
49
+ }
50
+ return this.create(rest);
51
+ }
52
+ delete(id) {
53
+ if (typeof id === 'string') {
54
+ return this.repository.delete({ id });
55
+ }
56
+ return this.repository.delete(id);
57
+ }
58
+ bulkDelete(criteria) {
59
+ return this.repository.bulkDelete(criteria);
60
+ }
61
+ };
62
+ BaseService2 = __decorate([
63
+ injectable(),
64
+ __metadata("design:paramtypes", [typeof (_a = typeof IBaseMongoRepository !== "undefined" && IBaseMongoRepository) === "function" ? _a : Object])
65
+ ], BaseService2);export{BaseService2};//# sourceMappingURL=BaseService.js.map
@@ -0,0 +1 @@
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;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,CAAC,U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C;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"}
@@ -0,0 +1 @@
1
+ import 'reflect-metadata';
@@ -0,0 +1,54 @@
1
+ export interface Client<T> {
2
+ connection: T;
3
+ connect(): Promise<unknown>;
4
+ disconnect(): Promise<unknown>;
5
+ }
6
+ export type ConnectionFactory<T, K> = (config: K) => Promise<Client<T>>;
7
+ export interface Connection<T> {
8
+ client: Client<T>;
9
+ ttl: number;
10
+ lastUsed: number;
11
+ createdAt: Date;
12
+ requestCount: number;
13
+ }
14
+ export interface PoolConfig {
15
+ ttlMs: number;
16
+ cleanupIntervalMs: number;
17
+ }
18
+ export declare class ConnectionPoolManager<T, K> {
19
+ name: string;
20
+ private connectionFactory;
21
+ private readonly config;
22
+ private pool;
23
+ private pendingConnections;
24
+ private cleanupTimer;
25
+ private totalRequests;
26
+ private cacheHits;
27
+ constructor(name: string, connectionFactory: ConnectionFactory<T, K>, config: PoolConfig);
28
+ private logger;
29
+ private getExistingConnection;
30
+ private removeConnection;
31
+ private isConnectionHealthy;
32
+ private refreshConnection;
33
+ getConnection(tenantId: string, config: K): Promise<T>;
34
+ private createNewConnection;
35
+ private storeConnection;
36
+ private startCleanupTask;
37
+ private stopCleanupTask;
38
+ private cleanupExpiredConnections;
39
+ shutdown(): Promise<void>;
40
+ getStats(): {
41
+ totalConnections: number;
42
+ activeConnections: number;
43
+ tenantCount: number;
44
+ totalRequests: number;
45
+ cacheHitRate: number;
46
+ connections: {
47
+ tenantId: string;
48
+ lastUsed: number;
49
+ ttlRemaining: number;
50
+ requestCount: number;
51
+ isHealthy: boolean;
52
+ }[];
53
+ };
54
+ }
@@ -0,0 +1,163 @@
1
+ class ConnectionPoolManager {
2
+ name;
3
+ connectionFactory;
4
+ config;
5
+ pool;
6
+ pendingConnections = new Map();
7
+ cleanupTimer = null;
8
+ totalRequests = 0;
9
+ cacheHits = 0;
10
+ constructor(name, connectionFactory, config) {
11
+ this.name = name;
12
+ this.connectionFactory = connectionFactory;
13
+ this.config = config;
14
+ this.pool = new Map();
15
+ }
16
+ // TODO: Use CDM logger
17
+ logger(level, message, ...params) {
18
+ console[level](`[${this.name} Pool] ${message}`, ...params);
19
+ }
20
+ async getExistingConnection(tenantId) {
21
+ const connection = this.pool.get(tenantId);
22
+ if (!connection) {
23
+ return null;
24
+ }
25
+ // Refresh connection TTL and last used time
26
+ this.refreshConnection(tenantId);
27
+ return connection;
28
+ }
29
+ async removeConnection(tenantId) {
30
+ const connection = this.pool.get(tenantId);
31
+ if (!connection)
32
+ return;
33
+ try {
34
+ await connection.client.disconnect();
35
+ this.pool.delete(tenantId);
36
+ this.logger('log', `🗑️ Removed connection for tenant: ${tenantId}`);
37
+ if (this.pool.size === 0) {
38
+ this.stopCleanupTask(); // Stop cleanup task if no connections are left
39
+ }
40
+ }
41
+ catch (error) {
42
+ this.logger('error', `❌ Failed to disconnect connection for tenant: ${tenantId}`, error);
43
+ }
44
+ }
45
+ // eslint-disable-next-line class-methods-use-this
46
+ isConnectionHealthy(connection) {
47
+ const now = Date.now();
48
+ const age = now - connection.createdAt.getTime();
49
+ return age < connection.ttl;
50
+ }
51
+ refreshConnection(tenantId) {
52
+ const connection = this.pool.get(tenantId);
53
+ if (!connection)
54
+ return;
55
+ connection.lastUsed = Date.now();
56
+ connection.requestCount += 1;
57
+ connection.ttl = Date.now() + this.config.ttlMs;
58
+ }
59
+ async getConnection(tenantId, config) {
60
+ this.totalRequests += 1;
61
+ try {
62
+ // Check if there's an existing connection for the tenant
63
+ const existingConnection = await this.getExistingConnection(tenantId);
64
+ if (existingConnection) {
65
+ this.logger('log', `♻️ Reusing existing connection for tenant: ${tenantId}`);
66
+ this.cacheHits += 1;
67
+ return existingConnection.client.connection;
68
+ }
69
+ }
70
+ catch (error) {
71
+ this.logger('error', `❌ Error checking existing connection for ${tenantId}:`, error);
72
+ }
73
+ // If connection is already being created → wait for it
74
+ if (this.pendingConnections.has(tenantId)) {
75
+ this.logger('log', `⏳ Waiting for pending connection for tenant: ${tenantId}`);
76
+ return (await this.pendingConnections.get(tenantId))?.connection;
77
+ }
78
+ // Create a new connection for the tenant
79
+ this.logger('log', `🔧 Creating new connection for tenant: ${tenantId}`);
80
+ const connectionPromise = this.createNewConnection(config)
81
+ .then((connection) => {
82
+ this.logger('log', `✅ Connection created for tenant: ${tenantId}`);
83
+ this.storeConnection(tenantId, connection);
84
+ return connection;
85
+ })
86
+ .catch((error) => {
87
+ this.logger('error', `❌ Failed to create connection for tenant ${tenantId}:`, error);
88
+ throw error;
89
+ })
90
+ .finally(() => {
91
+ this.pendingConnections.delete(tenantId);
92
+ });
93
+ this.pendingConnections.set(tenantId, connectionPromise);
94
+ return (await connectionPromise).connection;
95
+ }
96
+ async createNewConnection(config) {
97
+ const dbConnection = await this.connectionFactory(config);
98
+ await dbConnection.connect();
99
+ return dbConnection;
100
+ }
101
+ storeConnection(tenantId, client) {
102
+ const now = new Date();
103
+ const connection = {
104
+ client,
105
+ ttl: now.getTime() + this.config.ttlMs,
106
+ lastUsed: now.getTime(),
107
+ createdAt: now,
108
+ requestCount: 1,
109
+ };
110
+ this.pool.set(tenantId, connection);
111
+ this.logger('log', `📦 Stored connection for tenant: ${tenantId}`);
112
+ this.startCleanupTask(); // Start cleanup task when a new connection is stored
113
+ }
114
+ startCleanupTask() {
115
+ if (this.cleanupTimer) {
116
+ return; // Cleanup task already running
117
+ }
118
+ this.cleanupTimer = setInterval(() => {
119
+ this.cleanupExpiredConnections();
120
+ }, this.config.cleanupIntervalMs);
121
+ }
122
+ stopCleanupTask() {
123
+ if (this.cleanupTimer) {
124
+ clearInterval(this.cleanupTimer);
125
+ this.cleanupTimer = null;
126
+ }
127
+ }
128
+ cleanupExpiredConnections() {
129
+ const expiredConnections = Array.from(this.pool.entries())
130
+ .filter(
131
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
132
+ ([_, connection]) => () => !this.isConnectionHealthy(connection))
133
+ .map(([key]) => key);
134
+ this.logger('log', `🧹 Cleaning up ${expiredConnections.length} expired connections`);
135
+ expiredConnections.map(this.removeConnection.bind(this));
136
+ }
137
+ async shutdown() {
138
+ this.logger('log', '🔄 Shutting down ConnectionPoolManager...');
139
+ // Stop timers
140
+ this.stopCleanupTask();
141
+ // Close all connections
142
+ await Promise.allSettled(Array.from(this.pool.keys()).map(this.removeConnection.bind(this)));
143
+ this.logger('log', '✅ ConnectionPoolManager shutdown complete');
144
+ }
145
+ getStats() {
146
+ const now = Date.now();
147
+ const connections = Array.from(this.pool.entries()).map(([tenantId, conn]) => ({
148
+ tenantId,
149
+ lastUsed: conn.lastUsed,
150
+ ttlRemaining: Math.max(0, conn.ttl - now),
151
+ requestCount: conn.requestCount,
152
+ isHealthy: this.isConnectionHealthy(conn),
153
+ }));
154
+ return {
155
+ totalConnections: this.pool.size,
156
+ activeConnections: connections.filter((c) => c.isHealthy).length,
157
+ tenantCount: new Set(connections.map((c) => c.tenantId)).size,
158
+ totalRequests: this.totalRequests,
159
+ cacheHitRate: this.totalRequests > 0 ? (this.cacheHits / this.totalRequests) * 100 : 0,
160
+ connections,
161
+ };
162
+ }
163
+ }export{ConnectionPoolManager};//# sourceMappingURL=ConnectionPoolManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConnectionPoolManager.js","sources":["../../src/services/ConnectionPoolManager.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nexport interface Client<T> {\n connection: T; // The actual client/connection object\n connect(): Promise<unknown>;\n disconnect(): Promise<unknown>;\n}\n\nexport type ConnectionFactory<T, K> = (config: K) => Promise<Client<T>>;\n\nexport interface Connection<T> {\n client: Client<T>;\n ttl: number;\n lastUsed: number;\n createdAt: Date;\n requestCount: number;\n}\n\nexport interface PoolConfig {\n ttlMs: number;\n cleanupIntervalMs: number;\n}\n\nexport class ConnectionPoolManager<T, K> {\n private pool: Map<string, Connection<T>>;\n\n private pendingConnections: Map<string, Promise<Client<T>>> = new Map();\n\n private cleanupTimer: NodeJS.Timer | null = null;\n\n private totalRequests: number = 0;\n\n private cacheHits: number = 0;\n\n constructor(\n public name: string,\n private connectionFactory: ConnectionFactory<T, K>,\n private readonly config: PoolConfig,\n ) {\n this.pool = new Map();\n }\n\n // TODO: Use CDM logger\n private logger(level: 'log' | 'error', message: string, ...params): void {\n console[level](`[${this.name} Pool] ${message}`, ...params);\n }\n\n private async getExistingConnection(tenantId: string): Promise<Connection<T> | null> {\n const connection = this.pool.get(tenantId);\n\n if (!connection) {\n return null;\n }\n\n // Refresh connection TTL and last used time\n this.refreshConnection(tenantId);\n return connection;\n }\n\n private async removeConnection(tenantId: string): Promise<void> {\n const connection = this.pool.get(tenantId);\n\n if (!connection) return;\n\n try {\n await connection.client.disconnect();\n this.pool.delete(tenantId);\n this.logger('log', `🗑️ Removed connection for tenant: ${tenantId}`);\n\n if (this.pool.size === 0) {\n this.stopCleanupTask(); // Stop cleanup task if no connections are left\n }\n } catch (error) {\n this.logger('error', `❌ Failed to disconnect connection for tenant: ${tenantId}`, error);\n }\n }\n\n // eslint-disable-next-line class-methods-use-this\n private isConnectionHealthy(connection: Connection<T>): boolean {\n const now = Date.now();\n const age = now - connection.createdAt.getTime();\n return age < connection.ttl;\n }\n\n private refreshConnection(tenantId: string): void {\n const connection = this.pool.get(tenantId);\n\n if (!connection) return;\n\n connection.lastUsed = Date.now();\n connection.requestCount += 1;\n connection.ttl = Date.now() + this.config.ttlMs;\n }\n\n public async getConnection(tenantId: string, config: K): Promise<T> {\n this.totalRequests += 1;\n\n try {\n // Check if there's an existing connection for the tenant\n const existingConnection = await this.getExistingConnection(tenantId);\n\n if (existingConnection) {\n this.logger('log', `♻️ Reusing existing connection for tenant: ${tenantId}`);\n this.cacheHits += 1;\n return existingConnection.client.connection;\n }\n } catch (error) {\n this.logger('error', `❌ Error checking existing connection for ${tenantId}:`, error);\n }\n\n // If connection is already being created → wait for it\n if (this.pendingConnections.has(tenantId)) {\n this.logger('log', `⏳ Waiting for pending connection for tenant: ${tenantId}`);\n return (await this.pendingConnections.get(tenantId))?.connection;\n }\n\n // Create a new connection for the tenant\n this.logger('log', `🔧 Creating new connection for tenant: ${tenantId}`);\n\n const connectionPromise = this.createNewConnection(config)\n .then((connection: Client<T>) => {\n this.logger('log', `✅ Connection created for tenant: ${tenantId}`);\n this.storeConnection(tenantId, connection);\n return connection;\n })\n .catch((error) => {\n this.logger('error', `❌ Failed to create connection for tenant ${tenantId}:`, error);\n throw error;\n })\n .finally(() => {\n this.pendingConnections.delete(tenantId);\n });\n\n this.pendingConnections.set(tenantId, connectionPromise);\n return (await connectionPromise).connection;\n }\n\n private async createNewConnection(config: K): Promise<Client<T>> {\n const dbConnection = await this.connectionFactory(config);\n await dbConnection.connect();\n return dbConnection;\n }\n\n private storeConnection(tenantId: string, client: Client<T>): void {\n const now = new Date();\n const connection: Connection<T> = {\n client,\n ttl: now.getTime() + this.config.ttlMs,\n lastUsed: now.getTime(),\n createdAt: now,\n requestCount: 1,\n };\n\n this.pool.set(tenantId, connection);\n this.logger('log', `📦 Stored connection for tenant: ${tenantId}`);\n this.startCleanupTask(); // Start cleanup task when a new connection is stored\n }\n\n private startCleanupTask(): void {\n if (this.cleanupTimer) {\n return; // Cleanup task already running\n }\n\n this.cleanupTimer = setInterval(() => {\n this.cleanupExpiredConnections();\n }, this.config.cleanupIntervalMs);\n }\n\n private stopCleanupTask(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n }\n\n private cleanupExpiredConnections(): void {\n const expiredConnections: string[] = Array.from(this.pool.entries())\n .filter(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n ([_, connection]) =>\n () =>\n !this.isConnectionHealthy(connection),\n )\n .map(([key]) => key);\n\n this.logger('log', `🧹 Cleaning up ${expiredConnections.length} expired connections`);\n expiredConnections.map(this.removeConnection.bind(this));\n }\n\n public async shutdown(): Promise<void> {\n this.logger('log', '🔄 Shutting down ConnectionPoolManager...');\n\n // Stop timers\n this.stopCleanupTask();\n\n // Close all connections\n await Promise.allSettled(Array.from(this.pool.keys()).map(this.removeConnection.bind(this)));\n this.logger('log', '✅ ConnectionPoolManager shutdown complete');\n }\n\n getStats() {\n const now = Date.now();\n const connections = Array.from(this.pool.entries()).map(([tenantId, conn]) => ({\n tenantId,\n lastUsed: conn.lastUsed,\n ttlRemaining: Math.max(0, conn.ttl - now),\n requestCount: conn.requestCount,\n isHealthy: this.isConnectionHealthy(conn),\n }));\n\n return {\n totalConnections: this.pool.size,\n activeConnections: connections.filter((c) => c.isHealthy).length,\n tenantCount: new Set(connections.map((c) => c.tenantId)).size,\n totalRequests: this.totalRequests,\n cacheHitRate: this.totalRequests > 0 ? (this.cacheHits / this.totalRequests) * 100 : 0,\n connections,\n };\n }\n}\n"],"names":[],"mappings":"MAsBa,qBAAqB,CAAA;AAYnB,IAAA,IAAA,CAAA;AACC,IAAA,iBAAA,CAAA;AACS,IAAA,MAAA,CAAA;AAbb,IAAA,IAAI,CAA6B;AAEjC,IAAA,kBAAkB,GAAoC,IAAI,GAAG,EAAE,CAAC;IAEhE,YAAY,GAAwB,IAAI,CAAC;IAEzC,aAAa,GAAW,CAAC,CAAC;IAE1B,SAAS,GAAW,CAAC,CAAC;AAE9B,IAAA,WAAA,CACW,IAAY,EACX,iBAA0C,EACjC,MAAkB,EAAA;QAF5B,IAAI,CAAA,IAAA,GAAJ,IAAI,CAAQ;QACX,IA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GAAG,CAAC;YACzC,YAAY,EAAE,IAAI,CAAC,YAAY;AAC/B,YAAA,SAAS,EAAE,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC;AAC5C,SAAA,CAAC,CAAC,CAAC;QAEJ,OAAO;AACH,YAAA,gBAAgB,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI;AAChC,YAAA,iBAAiB,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM;AAChE,YAAA,WAAW,EAAE,IAAI,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI;YAC7D,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,YAAY,EAAE,IAAI,CAAC,aAAa,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,aAAa,IAAI,GAAG,GAAG,CAAC;YACtF,WAAW;SACd,CAAC;KACL;AACJ"}
@@ -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":[null],"names":[],"mappings":"yPAYsB,IAAA,gBAAgB,GAA/B,MAAe,gBAAgB,CAAA;AAOb,IAAA,MAAA,CAAA;IAFrB,WAEqB,CAAA,MAAqB,EAGtC,MAAyB,EAA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AC,mBAAmB,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;KACxE;IAED,MAAM,CAAC,IAAW,EAAE,SAAmB,EAAA;AACnC,QAAA,OAAO,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC;KAC3E;AAED,IAAA,MAAM,CAAC,EAAU,EAAE,IAAO,EAAE,SAAmB,EAAA;AAC3C,QAAA,OAAO,IAAI,CAAC,UAAU,CAAI,mBAAmB,CAAC,MAAM,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC;KAClF;AAES,IAAA,MAAM,UAAU,CAAiB,OAAe,EAAE,MAAU,EAAA;AAClE,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
+ {"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,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,mBAAmB,CAAC,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;KAC9D;AAED,IAAA,GAAG,CAAC,EAAmC,EAAA;AACnC,QAAA,OAAO,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;KAC3D;AAED,IAAA,MAAM,CAAC,OAA8B,EAAA;QACjC,OAAO,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,MAAM,EAAE,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';
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":[null],"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;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,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,EAA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E,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,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,EAAE,CAAC,CAAC;KACxC;AAED,IAAA,MAAM,CAAC,OAAgC,EAAA;QACnC,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;KAC1C;AAED,IAAA,QAAQ,CAAC,GAAa,EAAA;QAClB,OAAO,IAAI,CAAC,UAAU,CAAC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5 @@
1
+ export * from './BaseService';
2
+ export * from './BaseProxyService';
3
+ export * from './ConnectionPoolManager';
1
4
  export * from './base-service';
2
5
  export * from './base-proxy-service';
@@ -0,0 +1,16 @@
1
+ import { Schema } from 'mongoose';
2
+ export declare const commonModelSchemaOptions2: {
3
+ timestamps: boolean;
4
+ toJSON: {
5
+ virtuals: boolean;
6
+ transform(doc: any, ret: any): any;
7
+ };
8
+ toObject: {
9
+ virtuals: boolean;
10
+ getters: boolean;
11
+ transform(doc: any, ret: any): any;
12
+ };
13
+ };
14
+ export declare const addIdVirtualFields2: (schema: Schema) => Schema<any, import("mongoose").Model<any, any, any, any, any>, {}, {}, {}, {}, import("mongoose").DefaultSchemaOptions, {
15
+ [x: string]: any;
16
+ }>;
@@ -0,0 +1,40 @@
1
+ const commonModelSchemaOptions2 = {
2
+ timestamps: true,
3
+ toJSON: {
4
+ virtuals: true,
5
+ transform(doc, ret) {
6
+ ret.id = ret._id.toString();
7
+ delete ret.__v;
8
+ // Uncomment if you don't want _id in output
9
+ // delete ret._id;
10
+ return ret;
11
+ },
12
+ },
13
+ toObject: {
14
+ virtuals: true,
15
+ getters: true,
16
+ transform(doc, ret) {
17
+ ret.id = ret._id.toString();
18
+ delete ret.__v;
19
+ // Uncomment if you don't want _id in output
20
+ // delete ret._id;
21
+ return ret;
22
+ },
23
+ },
24
+ };
25
+ const addIdVirtualFields2 = (schema) => {
26
+ // Add id virtual getter
27
+ schema.virtual('id').get(function () {
28
+ return this._id.toHexString();
29
+ });
30
+ // Ensure virtuals are included in JSON
31
+ schema.set('toJSON', {
32
+ virtuals: true,
33
+ transform: (_, ret) => {
34
+ ret.id = ret._id.toString();
35
+ delete ret.__v;
36
+ return ret;
37
+ },
38
+ });
39
+ return schema;
40
+ };export{addIdVirtualFields2,commonModelSchemaOptions2};//# sourceMappingURL=common-options-v2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common-options-v2.js","sources":["../../../src/store/models/common-options-v2.ts"],"sourcesContent":["/* eslint-disable no-underscore-dangle */\n/* eslint-disable no-param-reassign */\nimport { Schema } from 'mongoose';\n\nexport const commonModelSchemaOptions2 = {\n timestamps: true,\n toJSON: {\n virtuals: true,\n transform(doc, ret) {\n ret.id = ret._id.toString();\n delete ret.__v;\n // Uncomment if you don't want _id in output\n // delete ret._id;\n return ret;\n },\n },\n toObject: {\n virtuals: true,\n getters: true,\n transform(doc, ret) {\n ret.id = ret._id.toString();\n delete ret.__v;\n // Uncomment if you don't want _id in output\n // delete ret._id;\n return ret;\n },\n },\n};\n\nexport const addIdVirtualFields2 = (schema: Schema) => {\n // Add id virtual getter\n schema.virtual('id').get(function () {\n return (this._id as any).toHexString();\n });\n\n // Ensure virtuals are included in JSON\n schema.set('toJSON', {\n virtuals: true,\n transform: (_, ret) => {\n ret.id = ret._id.toString();\n delete ret.__v;\n return ret;\n },\n });\n\n return schema;\n};\n"],"names":[],"mappings":"AAIa,MAAA,yBAAyB,GAAG;AACrC,IAAA,UAAU,EAAE,IAAI;AAChB,IAAA,MAAM,EAAE;AACJ,QAAA,QAAQ,EAAE,IAAI;QACd,SAAS,CAAC,GAAG,EAAE,GAAG,EAAA;YACd,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;YAC5B,OAAO,GAAG,CAAC,GAAG,CAAC;;;AAGf,YAAA,OAAO,GAAG,CAAC;SACd;AACJ,KAAA;AACD,IAAA,QAAQ,EAAE;AACN,QAAA,QAAQ,EAAE,IAAI;AACd,QAAA,OAAO,EAAE,IAAI;QACb,SAAS,CAAC,GAAG,EAAE,GAAG,EAAA;YACd,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;YAC5B,OAAO,GAAG,CAAC,GAAG,CAAC;;;AAGf,YAAA,OAAO,GAAG,CAAC;SACd;AACJ,KAAA;EACH;AAEW,MAAA,mBAAmB,GAAG,CAAC,MAAc,KAAI;;AAElD,IAAA,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,YAAA;AACrB,QAAA,OAAQ,IAAI,CAAC,GAAW,CAAC,WAAW,EAAE,CAAC;AAC3C,KAAC,CAAC,CAAC;;AAGH,IAAA,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE;AACjB,QAAA,QAAQ,EAAE,IAAI;AACd,QAAA,SAAS,EAAE,CAAC,CAAC,EAAE,GAAG,KAAI;YAClB,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;YAC5B,OAAO,GAAG,CAAC,GAAG,CAAC;AACf,YAAA,OAAO,GAAG,CAAC;SACd;AACJ,KAAA,CAAC,CAAC;AAEH,IAAA,OAAO,MAAM,CAAC;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"common-options.js","sources":["../../../src/store/models/common-options.ts"],"sourcesContent":[null],"names":[],"mappings":"AAEa,MAAA,uBAAuB,GAAG;AACnC,IAAA,UAAU,EAAE,IAAI;AAChB,IAAA,MAAM,EAAE;AACJ,QAAA,QAAQ,EAAE,IAAI;AACjB,KAAA;AACD,IAAA,QAAQ,EAAE;AACN,QAAA,QAAQ,EAAE,IAAI;AACd,QAAA,OAAO,EAAE,IAAI;QACb,SAAS,CAAC,GAAG,EAAE,GAAG,EAAA;YACd,OAAO,GAAG,CAAC,GAAG,CAAC;YACf,OAAO,GAAG,CAAC,GAAG,CAAC;SAClB;AACJ,KAAA;EACH;AAEW,MAAA,kBAAkB,GAAG,CAAC,MAAc,KAAI;AACjD,IAAA,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE;AACjB,QAAA,QAAQ,EAAE,IAAI;AACjB,KAAA,CAAC,CAAC;AACH,IAAA,OAAO,MAAM,CAAC;AAClB"}
1
+ {"version":3,"file":"common-options.js","sources":["../../../src/store/models/common-options.ts"],"sourcesContent":["import { Schema } from 'mongoose';\n\nexport const commonModeSchemaOptions = {\n timestamps: true,\n toJSON: {\n virtuals: true,\n },\n toObject: {\n virtuals: true,\n getters: true,\n transform(doc, ret) {\n delete ret.__v;\n delete ret._id;\n },\n },\n};\n\nexport const addIdVirtualFields = (schema: Schema) => {\n schema.set('toJSON', {\n virtuals: true,\n });\n return schema;\n};\n"],"names":[],"mappings":"AAEa,MAAA,uBAAuB,GAAG;AACnC,IAAA,UAAU,EAAE,IAAI;AAChB,IAAA,MAAM,EAAE;AACJ,QAAA,QAAQ,EAAE,IAAI;AACjB,KAAA;AACD,IAAA,QAAQ,EAAE;AACN,QAAA,QAAQ,EAAE,IAAI;AACd,QAAA,OAAO,EAAE,IAAI;QACb,SAAS,CAAC,GAAG,EAAE,GAAG,EAAA;YACd,OAAO,GAAG,CAAC,GAAG,CAAC;YACf,OAAO,GAAG,CAAC,GAAG,CAAC;SAClB;AACJ,KAAA;EACH;AAEW,MAAA,kBAAkB,GAAG,CAAC,MAAc,KAAI;AACjD,IAAA,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE;AACjB,QAAA,QAAQ,EAAE,IAAI;AACjB,KAAA,CAAC,CAAC;AACH,IAAA,OAAO,MAAM,CAAC;AAClB"}
@@ -1 +1,2 @@
1
+ export * from './common-options-v2';
1
2
  export * from './common-options';
@@ -0,0 +1,72 @@
1
+ import { CdmLogger } from '@cdm-logger/core';
2
+ import { Connection, FilterQuery, Model, PipelineStage, UpdateQuery } from 'mongoose';
3
+ import { GetAllArgs, ISort, IBaseMongoRepository, IMongoOptions, AsDomainType, CreateType, UpdateType } from 'common/server';
4
+ export declare class BaseMongoRepository<SchemaType> implements IBaseMongoRepository<SchemaType> {
5
+ private modelFunc;
6
+ private options;
7
+ protected logger: CdmLogger.ILogger;
8
+ model: Model<SchemaType & {
9
+ id: string;
10
+ }>;
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;
17
+ /**
18
+ * Transforms a document to the domain model format
19
+ */
20
+ protected transformDocument(doc: any): AsDomainType<SchemaType> | null;
21
+ /**
22
+ * Transforms an array of documents
23
+ */
24
+ protected transformDocuments(docs: SchemaType[]): AsDomainType<SchemaType>[];
25
+ /**
26
+ * Maps API criteria with 'id' to MongoDB criteria with '_id'
27
+ */
28
+ private mapConditions;
29
+ /**
30
+ * Computes sort object from GetAllArgs sort parameter
31
+ * Handles both string-based and object-based sort specifications
32
+ */
33
+ protected computeSort(sort: ISort | string | ISort[]): Record<string, 1 | -1>;
34
+ /**
35
+ * Prepares an aggregation pipeline with standard stages
36
+ * @param options Query options including filtering, sorting, pagination
37
+ * @param customPipeline Optional custom pipeline stages to include
38
+ * @returns Complete MongoDB aggregation pipeline
39
+ */
40
+ protected preparePipeline(options: GetAllArgs<SchemaType>, customPipeline?: PipelineStage[]): PipelineStage[];
41
+ /**
42
+ * Execute an aggregation pipeline and transform the results
43
+ */
44
+ protected aggregate(pipeline: PipelineStage[]): Promise<AsDomainType<SchemaType>[]>;
45
+ count(conditions?: FilterQuery<SchemaType>): Promise<number>;
46
+ get(conditions?: FilterQuery<SchemaType>, selectedFields?: string): Promise<AsDomainType<SchemaType> | null>;
47
+ find(conditions: Partial<FilterQuery<SchemaType>>, selectedFields?: string): Promise<AsDomainType<SchemaType> | null>;
48
+ getAll(options: GetAllArgs<SchemaType>): Promise<AsDomainType<SchemaType>[]>;
49
+ /**
50
+ * Get all documents using aggregation pipeline
51
+ */
52
+ getAllWithPipeline(options: GetAllArgs<SchemaType>, customPipeline?: PipelineStage[]): Promise<AsDomainType<SchemaType>[]>;
53
+ getAllWithCount(options: GetAllArgs<SchemaType>): Promise<{
54
+ data: AsDomainType<SchemaType>[];
55
+ totalCount: number;
56
+ }>;
57
+ /**
58
+ * Get all documents with count using aggregation pipeline
59
+ */
60
+ getAllWithCountAndPipeline(options: GetAllArgs<SchemaType>, customPipeline?: PipelineStage[]): Promise<{
61
+ data: AsDomainType<SchemaType>[];
62
+ totalCount: number;
63
+ }>;
64
+ create<T = CreateType<SchemaType>>(data: T): Promise<AsDomainType<SchemaType>>;
65
+ bulkCreate<T = CreateType<SchemaType>>(data: T[]): Promise<AsDomainType<SchemaType>[]>;
66
+ upsert<T = UpdateType<SchemaType>>(conditions: FilterQuery<SchemaType>, update: T, options?: Record<string, unknown>): Promise<AsDomainType<SchemaType>>;
67
+ update<T = UpdateType<SchemaType>>(criteria: FilterQuery<SchemaType>, update: T | UpdateQuery<SchemaType>, options?: Record<string, unknown>): Promise<AsDomainType<SchemaType>>;
68
+ bulkUpdate<T = UpdateType<SchemaType>>(criteria: FilterQuery<SchemaType>, update: T | UpdateQuery<SchemaType>, options?: Record<string, unknown>): Promise<AsDomainType<SchemaType>[]>;
69
+ delete(criteria: FilterQuery<SchemaType>): Promise<boolean>;
70
+ bulkDelete(criteria: FilterQuery<SchemaType>): Promise<number>;
71
+ bulkGet(ids: string[], selectedFields?: string): Promise<AsDomainType<SchemaType>[]>;
72
+ }