@ciscode/database-kit 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +206 -0
  2. package/LICENSE +21 -0
  3. package/README.md +446 -0
  4. package/dist/adapters/mongo.adapter.d.ts +44 -0
  5. package/dist/adapters/mongo.adapter.d.ts.map +1 -0
  6. package/dist/adapters/mongo.adapter.js +146 -0
  7. package/dist/adapters/mongo.adapter.js.map +1 -0
  8. package/dist/adapters/postgres.adapter.d.ts +49 -0
  9. package/dist/adapters/postgres.adapter.d.ts.map +1 -0
  10. package/dist/adapters/postgres.adapter.js +229 -0
  11. package/dist/adapters/postgres.adapter.js.map +1 -0
  12. package/dist/config/database.config.d.ts +55 -0
  13. package/dist/config/database.config.d.ts.map +1 -0
  14. package/dist/config/database.config.js +122 -0
  15. package/dist/config/database.config.js.map +1 -0
  16. package/dist/config/database.constants.d.ts +41 -0
  17. package/dist/config/database.constants.d.ts.map +1 -0
  18. package/dist/config/database.constants.js +45 -0
  19. package/dist/config/database.constants.js.map +1 -0
  20. package/dist/contracts/database.contracts.d.ts +191 -0
  21. package/dist/contracts/database.contracts.d.ts.map +1 -0
  22. package/dist/contracts/database.contracts.js +21 -0
  23. package/dist/contracts/database.contracts.js.map +1 -0
  24. package/dist/database-kit.module.d.ts +71 -0
  25. package/dist/database-kit.module.d.ts.map +1 -0
  26. package/dist/database-kit.module.js +158 -0
  27. package/dist/database-kit.module.js.map +1 -0
  28. package/dist/filters/database-exception.filter.d.ts +51 -0
  29. package/dist/filters/database-exception.filter.d.ts.map +1 -0
  30. package/dist/filters/database-exception.filter.js +236 -0
  31. package/dist/filters/database-exception.filter.js.map +1 -0
  32. package/dist/index.d.ts +19 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +78 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/middleware/database.decorators.d.ts +31 -0
  37. package/dist/middleware/database.decorators.d.ts.map +1 -0
  38. package/dist/middleware/database.decorators.js +39 -0
  39. package/dist/middleware/database.decorators.js.map +1 -0
  40. package/dist/services/database.service.d.ts +99 -0
  41. package/dist/services/database.service.d.ts.map +1 -0
  42. package/dist/services/database.service.js +205 -0
  43. package/dist/services/database.service.js.map +1 -0
  44. package/dist/services/logger.service.d.ts +63 -0
  45. package/dist/services/logger.service.d.ts.map +1 -0
  46. package/dist/services/logger.service.js +93 -0
  47. package/dist/services/logger.service.js.map +1 -0
  48. package/dist/utils/pagination.utils.d.ts +57 -0
  49. package/dist/utils/pagination.utils.d.ts.map +1 -0
  50. package/dist/utils/pagination.utils.js +113 -0
  51. package/dist/utils/pagination.utils.js.map +1 -0
  52. package/dist/utils/validation.utils.d.ts +60 -0
  53. package/dist/utils/validation.utils.d.ts.map +1 -0
  54. package/dist/utils/validation.utils.js +117 -0
  55. package/dist/utils/validation.utils.js.map +1 -0
  56. package/package.json +83 -0
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ // src/filters/database-exception.filter.ts
3
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
4
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
6
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
7
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
8
+ };
9
+ var DatabaseExceptionFilter_1;
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.DatabaseExceptionFilter = void 0;
12
+ const common_1 = require("@nestjs/common");
13
+ /**
14
+ * Global exception filter for handling database-related errors.
15
+ * Catches and formats various database errors into consistent HTTP responses.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * // In main.ts or a module
20
+ * app.useGlobalFilters(new DatabaseExceptionFilter());
21
+ *
22
+ * // Or in a module
23
+ * @Module({
24
+ * providers: [
25
+ * { provide: APP_FILTER, useClass: DatabaseExceptionFilter },
26
+ * ],
27
+ * })
28
+ * ```
29
+ */
30
+ let DatabaseExceptionFilter = DatabaseExceptionFilter_1 = class DatabaseExceptionFilter {
31
+ constructor() {
32
+ this.logger = new common_1.Logger(DatabaseExceptionFilter_1.name);
33
+ }
34
+ catch(exception, host) {
35
+ var _a, _b, _c;
36
+ const ctx = host.switchToHttp();
37
+ const response = ctx.getResponse();
38
+ const request = ctx.getRequest();
39
+ const { statusCode, message, error } = this.parseException(exception);
40
+ const errorResponse = {
41
+ statusCode,
42
+ message,
43
+ error,
44
+ timestamp: new Date().toISOString(),
45
+ path: (request === null || request === void 0 ? void 0 : request.url) || '/',
46
+ };
47
+ // Log the error
48
+ this.logError(exception, errorResponse);
49
+ (_c = (_b = (_a = response === null || response === void 0 ? void 0 : response.status) === null || _a === void 0 ? void 0 : _a.call(response, statusCode)) === null || _b === void 0 ? void 0 : _b.json) === null || _c === void 0 ? void 0 : _c.call(_b, errorResponse);
50
+ }
51
+ /**
52
+ * Parses an exception and extracts status code, message, and error type.
53
+ */
54
+ parseException(exception) {
55
+ // Handle NestJS HTTP exceptions
56
+ if (exception instanceof common_1.HttpException) {
57
+ const response = exception.getResponse();
58
+ const message = typeof response === 'string'
59
+ ? response
60
+ : response.message || exception.message;
61
+ return {
62
+ statusCode: exception.getStatus(),
63
+ message,
64
+ error: exception.name,
65
+ };
66
+ }
67
+ // Handle MongoDB errors
68
+ if (this.isMongoError(exception)) {
69
+ return this.parseMongoError(exception);
70
+ }
71
+ // Handle PostgreSQL/Knex errors
72
+ if (this.isKnexError(exception)) {
73
+ return this.parseKnexError(exception);
74
+ }
75
+ // Handle validation errors (class-validator)
76
+ if (this.isValidationError(exception)) {
77
+ return {
78
+ statusCode: common_1.HttpStatus.BAD_REQUEST,
79
+ message: exception.message,
80
+ error: 'ValidationError',
81
+ };
82
+ }
83
+ // Handle generic errors
84
+ if (exception instanceof Error) {
85
+ return {
86
+ statusCode: common_1.HttpStatus.INTERNAL_SERVER_ERROR,
87
+ message: exception.message || 'An unexpected error occurred',
88
+ error: exception.name || 'InternalServerError',
89
+ };
90
+ }
91
+ // Fallback for unknown errors
92
+ return {
93
+ statusCode: common_1.HttpStatus.INTERNAL_SERVER_ERROR,
94
+ message: 'An unexpected error occurred',
95
+ error: 'InternalServerError',
96
+ };
97
+ }
98
+ /**
99
+ * Checks if the exception is a MongoDB error.
100
+ */
101
+ isMongoError(exception) {
102
+ if (!exception || typeof exception !== 'object')
103
+ return false;
104
+ const err = exception;
105
+ return (err.name === 'MongoError' ||
106
+ err.name === 'MongoServerError' ||
107
+ err.name === 'MongooseError' ||
108
+ err.name === 'CastError' ||
109
+ err.name === 'ValidationError');
110
+ }
111
+ /**
112
+ * Parses MongoDB-specific errors.
113
+ */
114
+ parseMongoError(exception) {
115
+ const err = exception;
116
+ // Duplicate key error
117
+ if (err.code === 11000) {
118
+ return {
119
+ statusCode: common_1.HttpStatus.CONFLICT,
120
+ message: 'A record with this value already exists',
121
+ error: 'DuplicateKeyError',
122
+ };
123
+ }
124
+ // Cast error (invalid ObjectId, etc.)
125
+ if (err.name === 'CastError') {
126
+ return {
127
+ statusCode: common_1.HttpStatus.BAD_REQUEST,
128
+ message: 'Invalid ID format',
129
+ error: 'CastError',
130
+ };
131
+ }
132
+ // Mongoose validation error
133
+ if (err.name === 'ValidationError') {
134
+ return {
135
+ statusCode: common_1.HttpStatus.BAD_REQUEST,
136
+ message: err.message,
137
+ error: 'ValidationError',
138
+ };
139
+ }
140
+ return {
141
+ statusCode: common_1.HttpStatus.INTERNAL_SERVER_ERROR,
142
+ message: 'Database operation failed',
143
+ error: 'DatabaseError',
144
+ };
145
+ }
146
+ /**
147
+ * Checks if the exception is a Knex/PostgreSQL error.
148
+ */
149
+ isKnexError(exception) {
150
+ if (!exception || typeof exception !== 'object')
151
+ return false;
152
+ const err = exception;
153
+ // PostgreSQL error codes start with numbers
154
+ return typeof err.code === 'string' && /^[0-9A-Z]{5}$/.test(err.code);
155
+ }
156
+ /**
157
+ * Parses PostgreSQL/Knex-specific errors.
158
+ */
159
+ parseKnexError(exception) {
160
+ const err = exception;
161
+ // Unique constraint violation
162
+ if (err.code === '23505') {
163
+ return {
164
+ statusCode: common_1.HttpStatus.CONFLICT,
165
+ message: `A record with this value already exists${err.constraint ? ` (${err.constraint})` : ''}`,
166
+ error: 'UniqueConstraintViolation',
167
+ };
168
+ }
169
+ // Foreign key violation
170
+ if (err.code === '23503') {
171
+ return {
172
+ statusCode: common_1.HttpStatus.BAD_REQUEST,
173
+ message: 'Referenced record does not exist',
174
+ error: 'ForeignKeyViolation',
175
+ };
176
+ }
177
+ // Not null violation
178
+ if (err.code === '23502') {
179
+ return {
180
+ statusCode: common_1.HttpStatus.BAD_REQUEST,
181
+ message: 'Required field is missing',
182
+ error: 'NotNullViolation',
183
+ };
184
+ }
185
+ // Check constraint violation
186
+ if (err.code === '23514') {
187
+ return {
188
+ statusCode: common_1.HttpStatus.BAD_REQUEST,
189
+ message: 'Value does not meet constraint requirements',
190
+ error: 'CheckConstraintViolation',
191
+ };
192
+ }
193
+ // Connection errors
194
+ if (err.code === '08006' || err.code === '08001' || err.code === '08004') {
195
+ return {
196
+ statusCode: common_1.HttpStatus.SERVICE_UNAVAILABLE,
197
+ message: 'Database connection error',
198
+ error: 'ConnectionError',
199
+ };
200
+ }
201
+ return {
202
+ statusCode: common_1.HttpStatus.INTERNAL_SERVER_ERROR,
203
+ message: 'Database operation failed',
204
+ error: 'DatabaseError',
205
+ };
206
+ }
207
+ /**
208
+ * Checks if the exception is a validation error.
209
+ */
210
+ isValidationError(exception) {
211
+ if (!exception || typeof exception !== 'object')
212
+ return false;
213
+ const err = exception;
214
+ return err.name === 'ValidationError';
215
+ }
216
+ /**
217
+ * Logs the error with appropriate level and context.
218
+ */
219
+ logError(exception, errorResponse) {
220
+ const { statusCode, message, error, path } = errorResponse;
221
+ if (statusCode >= 500) {
222
+ this.logger.error(`[${error}] ${message} - ${path}`, exception instanceof Error ? exception.stack : undefined);
223
+ }
224
+ else if (statusCode >= 400) {
225
+ this.logger.warn(`[${error}] ${message} - ${path}`);
226
+ }
227
+ else {
228
+ this.logger.log(`[${error}] ${message} - ${path}`);
229
+ }
230
+ }
231
+ };
232
+ exports.DatabaseExceptionFilter = DatabaseExceptionFilter;
233
+ exports.DatabaseExceptionFilter = DatabaseExceptionFilter = DatabaseExceptionFilter_1 = __decorate([
234
+ (0, common_1.Catch)()
235
+ ], DatabaseExceptionFilter);
236
+ //# sourceMappingURL=database-exception.filter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database-exception.filter.js","sourceRoot":"","sources":["../../src/filters/database-exception.filter.ts"],"names":[],"mappings":";AAAA,2CAA2C;;;;;;;;;;AAE3C,2CAOwB;AAaxB;;;;;;;;;;;;;;;;GAgBG;AAEI,IAAM,uBAAuB,+BAA7B,MAAM,uBAAuB;IAA7B;QACc,WAAM,GAAG,IAAI,eAAM,CAAC,yBAAuB,CAAC,IAAI,CAAC,CAAC;IA8OvE,CAAC;IA5OG,KAAK,CAAC,SAAkB,EAAE,IAAmB;;QACzC,MAAM,GAAG,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QAChC,MAAM,QAAQ,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;QACnC,MAAM,OAAO,GAAG,GAAG,CAAC,UAAU,EAAE,CAAC;QAEjC,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;QAEtE,MAAM,aAAa,GAAkB;YACjC,UAAU;YACV,OAAO;YACP,KAAK;YACL,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,IAAI,EAAE,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,GAAG,KAAI,GAAG;SAC5B,CAAC;QAEF,gBAAgB;QAChB,IAAI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I,UAAU,IAAI,GAAG,EAAE,CAAC;YAC3B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,KAAK,KAAK,OAAO,MAAM,IAAI,EAAE,CAAC,CAAC;QACxD,CAAC;aAAM,CAAC;YACJ,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,KAAK,KAAK,OAAO,MAAM,IAAI,EAAE,CAAC,CAAC;QACvD,CAAC;IACL,CAAC;CACJ,CAAA;AA/OY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,cAAK,GAAE;GACK,uBAAuB,CA+OnC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @ciscode/database-kit
3
+ *
4
+ * A NestJS-friendly, OOP-style database library providing a unified
5
+ * repository API for MongoDB and PostgreSQL.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ export { DatabaseKitModule } from './database-kit.module';
10
+ export { DatabaseService } from './services/database.service';
11
+ export { LoggerService } from './services/logger.service';
12
+ export { InjectDatabase, InjectDatabaseByToken } from './middleware/database.decorators';
13
+ export { DatabaseExceptionFilter } from './filters/database-exception.filter';
14
+ export { DatabaseConfigHelper } from './config/database.config';
15
+ export { DATABASE_TOKEN, DATABASE_OPTIONS_TOKEN, ENV_KEYS, DEFAULTS } from './config/database.constants';
16
+ export { DatabaseType, DatabaseConfig, MongoDatabaseConfig, PostgresDatabaseConfig, DatabaseKitModuleOptions, DatabaseKitModuleAsyncOptions, InjectionToken, OptionalFactoryDependency, Repository, PageResult, PageOptions, MongoRepositoryOptions, PostgresEntityConfig, DATABASE_KIT_CONSTANTS, } from './contracts/database.contracts';
17
+ export { normalizePaginationOptions, calculatePagination, createPageResult, parseSortString, calculateOffset, } from './utils/pagination.utils';
18
+ export { isValidMongoId, isValidUuid, isPositiveInteger, sanitizeFilter, validateRequiredFields, pickFields, omitFields, } from './utils/validation.utils';
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAUH,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAM1D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAM1D,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAMzF,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAM9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,sBAAsB,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAMzG,OAAO,EAEH,YAAY,EACZ,cAAc,EACd,mBAAmB,EACnB,sBAAsB,EAGtB,wBAAwB,EACxB,6BAA6B,EAC7B,cAAc,EACd,yBAAyB,EAGzB,UAAU,EAGV,UAAU,EACV,WAAW,EAGX,sBAAsB,EACtB,oBAAoB,EAGpB,sBAAsB,GACzB,MAAM,gCAAgC,CAAC;AAMxC,OAAO,EACH,0BAA0B,EAC1B,mBAAmB,EACnB,gBAAgB,EAChB,eAAe,EACf,eAAe,GAClB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EACH,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,cAAc,EACd,sBAAsB,EACtB,UAAU,EACV,UAAU,GACb,MAAM,0BAA0B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ // src/index.ts
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.omitFields = exports.pickFields = exports.validateRequiredFields = exports.sanitizeFilter = exports.isPositiveInteger = exports.isValidUuid = exports.isValidMongoId = exports.calculateOffset = exports.parseSortString = exports.createPageResult = exports.calculatePagination = exports.normalizePaginationOptions = exports.DATABASE_KIT_CONSTANTS = exports.DEFAULTS = exports.ENV_KEYS = exports.DATABASE_OPTIONS_TOKEN = exports.DATABASE_TOKEN = exports.DatabaseConfigHelper = exports.DatabaseExceptionFilter = exports.InjectDatabaseByToken = exports.InjectDatabase = exports.LoggerService = exports.DatabaseService = exports.DatabaseKitModule = void 0;
5
+ /**
6
+ * @ciscode/database-kit
7
+ *
8
+ * A NestJS-friendly, OOP-style database library providing a unified
9
+ * repository API for MongoDB and PostgreSQL.
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ // =============================================================================
14
+ // PUBLIC API - Only export what host apps MUST use
15
+ // =============================================================================
16
+ // -----------------------------------------------------------------------------
17
+ // Module (Primary export)
18
+ // -----------------------------------------------------------------------------
19
+ var database_kit_module_1 = require("./database-kit.module");
20
+ Object.defineProperty(exports, "DatabaseKitModule", { enumerable: true, get: function () { return database_kit_module_1.DatabaseKitModule; } });
21
+ // -----------------------------------------------------------------------------
22
+ // Services (For direct injection if needed)
23
+ // -----------------------------------------------------------------------------
24
+ var database_service_1 = require("./services/database.service");
25
+ Object.defineProperty(exports, "DatabaseService", { enumerable: true, get: function () { return database_service_1.DatabaseService; } });
26
+ var logger_service_1 = require("./services/logger.service");
27
+ Object.defineProperty(exports, "LoggerService", { enumerable: true, get: function () { return logger_service_1.LoggerService; } });
28
+ // -----------------------------------------------------------------------------
29
+ // Decorators (For dependency injection)
30
+ // -----------------------------------------------------------------------------
31
+ var database_decorators_1 = require("./middleware/database.decorators");
32
+ Object.defineProperty(exports, "InjectDatabase", { enumerable: true, get: function () { return database_decorators_1.InjectDatabase; } });
33
+ Object.defineProperty(exports, "InjectDatabaseByToken", { enumerable: true, get: function () { return database_decorators_1.InjectDatabaseByToken; } });
34
+ // -----------------------------------------------------------------------------
35
+ // Filters (For global exception handling)
36
+ // -----------------------------------------------------------------------------
37
+ var database_exception_filter_1 = require("./filters/database-exception.filter");
38
+ Object.defineProperty(exports, "DatabaseExceptionFilter", { enumerable: true, get: function () { return database_exception_filter_1.DatabaseExceptionFilter; } });
39
+ // -----------------------------------------------------------------------------
40
+ // Configuration Helpers (For advanced configuration)
41
+ // -----------------------------------------------------------------------------
42
+ var database_config_1 = require("./config/database.config");
43
+ Object.defineProperty(exports, "DatabaseConfigHelper", { enumerable: true, get: function () { return database_config_1.DatabaseConfigHelper; } });
44
+ var database_constants_1 = require("./config/database.constants");
45
+ Object.defineProperty(exports, "DATABASE_TOKEN", { enumerable: true, get: function () { return database_constants_1.DATABASE_TOKEN; } });
46
+ Object.defineProperty(exports, "DATABASE_OPTIONS_TOKEN", { enumerable: true, get: function () { return database_constants_1.DATABASE_OPTIONS_TOKEN; } });
47
+ Object.defineProperty(exports, "ENV_KEYS", { enumerable: true, get: function () { return database_constants_1.ENV_KEYS; } });
48
+ Object.defineProperty(exports, "DEFAULTS", { enumerable: true, get: function () { return database_constants_1.DEFAULTS; } });
49
+ // -----------------------------------------------------------------------------
50
+ // Contracts (Types and Interfaces for consumers)
51
+ // -----------------------------------------------------------------------------
52
+ var database_contracts_1 = require("./contracts/database.contracts");
53
+ // Constants
54
+ Object.defineProperty(exports, "DATABASE_KIT_CONSTANTS", { enumerable: true, get: function () { return database_contracts_1.DATABASE_KIT_CONSTANTS; } });
55
+ // -----------------------------------------------------------------------------
56
+ // Utilities (For common operations)
57
+ // -----------------------------------------------------------------------------
58
+ var pagination_utils_1 = require("./utils/pagination.utils");
59
+ Object.defineProperty(exports, "normalizePaginationOptions", { enumerable: true, get: function () { return pagination_utils_1.normalizePaginationOptions; } });
60
+ Object.defineProperty(exports, "calculatePagination", { enumerable: true, get: function () { return pagination_utils_1.calculatePagination; } });
61
+ Object.defineProperty(exports, "createPageResult", { enumerable: true, get: function () { return pagination_utils_1.createPageResult; } });
62
+ Object.defineProperty(exports, "parseSortString", { enumerable: true, get: function () { return pagination_utils_1.parseSortString; } });
63
+ Object.defineProperty(exports, "calculateOffset", { enumerable: true, get: function () { return pagination_utils_1.calculateOffset; } });
64
+ var validation_utils_1 = require("./utils/validation.utils");
65
+ Object.defineProperty(exports, "isValidMongoId", { enumerable: true, get: function () { return validation_utils_1.isValidMongoId; } });
66
+ Object.defineProperty(exports, "isValidUuid", { enumerable: true, get: function () { return validation_utils_1.isValidUuid; } });
67
+ Object.defineProperty(exports, "isPositiveInteger", { enumerable: true, get: function () { return validation_utils_1.isPositiveInteger; } });
68
+ Object.defineProperty(exports, "sanitizeFilter", { enumerable: true, get: function () { return validation_utils_1.sanitizeFilter; } });
69
+ Object.defineProperty(exports, "validateRequiredFields", { enumerable: true, get: function () { return validation_utils_1.validateRequiredFields; } });
70
+ Object.defineProperty(exports, "pickFields", { enumerable: true, get: function () { return validation_utils_1.pickFields; } });
71
+ Object.defineProperty(exports, "omitFields", { enumerable: true, get: function () { return validation_utils_1.omitFields; } });
72
+ // =============================================================================
73
+ // NOT EXPORTED (Internal implementation details)
74
+ // =============================================================================
75
+ // ❌ MongoAdapter - Internal adapter, use DatabaseService instead
76
+ // ❌ PostgresAdapter - Internal adapter, use DatabaseService instead
77
+ // ❌ Internal helper functions
78
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,eAAe;;;AAEf;;;;;;;GAOG;AAEH,gFAAgF;AAChF,mDAAmD;AACnD,gFAAgF;AAEhF,gFAAgF;AAChF,0BAA0B;AAC1B,gFAAgF;AAEhF,6DAA0D;AAAjD,wHAAA,iBAAiB,OAAA;AAE1B,gFAAgF;AAChF,4CAA4C;AAC5C,gFAAgF;AAEhF,gEAA8D;AAArD,mHAAA,eAAe,OAAA;AACxB,4DAA0D;AAAjD,+GAAA,aAAa,OAAA;AAEtB,gFAAgF;AAChF,wCAAwC;AACxC,gFAAgF;AAEhF,wEAAyF;AAAhF,qHAAA,cAAc,OAAA;AAAE,4HAAA,qBAAqB,OAAA;AAE9C,gFAAgF;AAChF,0CAA0C;AAC1C,gFAAgF;AAEhF,iFAA8E;AAArE,oIAAA,uBAAuB,OAAA;AAEhC,gFAAgF;AAChF,qDAAqD;AACrD,gFAAgF;AAEhF,4DAAgE;AAAvD,uHAAA,oBAAoB,OAAA;AAC7B,kEAAyG;AAAhG,oHAAA,cAAc,OAAA;AAAE,4HAAA,sBAAsB,OAAA;AAAE,8GAAA,QAAQ,OAAA;AAAE,8GAAA,QAAQ,OAAA;AAEnE,gFAAgF;AAChF,iDAAiD;AACjD,gFAAgF;AAEhF,qEA0BwC;AAFpC,YAAY;AACZ,4HAAA,sBAAsB,OAAA;AAG1B,gFAAgF;AAChF,oCAAoC;AACpC,gFAAgF;AAEhF,6DAMkC;AAL9B,8HAAA,0BAA0B,OAAA;AAC1B,uHAAA,mBAAmB,OAAA;AACnB,oHAAA,gBAAgB,OAAA;AAChB,mHAAA,eAAe,OAAA;AACf,mHAAA,eAAe,OAAA;AAGnB,6DAQkC;AAP9B,kHAAA,cAAc,OAAA;AACd,+GAAA,WAAW,OAAA;AACX,qHAAA,iBAAiB,OAAA;AACjB,kHAAA,cAAc,OAAA;AACd,0HAAA,sBAAsB,OAAA;AACtB,8GAAA,UAAU,OAAA;AACV,8GAAA,UAAU,OAAA;AAGd,gFAAgF;AAChF,iDAAiD;AACjD,gFAAgF;AAEhF,iEAAiE;AACjE,oEAAoE;AACpE,8BAA8B"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Decorator to inject the DatabaseService instance.
3
+ *
4
+ * @example
5
+ * ```typescript
6
+ * @Injectable()
7
+ * export class UserService {
8
+ * constructor(@InjectDatabase() private readonly db: DatabaseService) {}
9
+ * }
10
+ * ```
11
+ */
12
+ export declare const InjectDatabase: () => ParameterDecorator;
13
+ /**
14
+ * Creates a custom injection decorator for a named database connection.
15
+ * Use this when working with multiple database connections.
16
+ *
17
+ * @param token - The token used when registering the database with forFeature()
18
+ * @returns Parameter decorator
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * const InjectAnalyticsDb = () => InjectDatabaseByToken('ANALYTICS_DB');
23
+ *
24
+ * @Injectable()
25
+ * export class AnalyticsService {
26
+ * constructor(@InjectAnalyticsDb() private readonly db: DatabaseService) {}
27
+ * }
28
+ * ```
29
+ */
30
+ export declare const InjectDatabaseByToken: (token: string) => ParameterDecorator;
31
+ //# sourceMappingURL=database.decorators.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.decorators.d.ts","sourceRoot":"","sources":["../../src/middleware/database.decorators.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;GAUG;AACH,eAAO,MAAM,cAAc,QAAO,kBAA4C,CAAC;AAE/E;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,qBAAqB,GAAI,OAAO,MAAM,KAAG,kBAAmC,CAAC"}
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ // src/middleware/database.decorators.ts
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.InjectDatabaseByToken = exports.InjectDatabase = void 0;
5
+ const common_1 = require("@nestjs/common");
6
+ const database_constants_1 = require("../config/database.constants");
7
+ /**
8
+ * Decorator to inject the DatabaseService instance.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * @Injectable()
13
+ * export class UserService {
14
+ * constructor(@InjectDatabase() private readonly db: DatabaseService) {}
15
+ * }
16
+ * ```
17
+ */
18
+ const InjectDatabase = () => (0, common_1.Inject)(database_constants_1.DATABASE_TOKEN);
19
+ exports.InjectDatabase = InjectDatabase;
20
+ /**
21
+ * Creates a custom injection decorator for a named database connection.
22
+ * Use this when working with multiple database connections.
23
+ *
24
+ * @param token - The token used when registering the database with forFeature()
25
+ * @returns Parameter decorator
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * const InjectAnalyticsDb = () => InjectDatabaseByToken('ANALYTICS_DB');
30
+ *
31
+ * @Injectable()
32
+ * export class AnalyticsService {
33
+ * constructor(@InjectAnalyticsDb() private readonly db: DatabaseService) {}
34
+ * }
35
+ * ```
36
+ */
37
+ const InjectDatabaseByToken = (token) => (0, common_1.Inject)(token);
38
+ exports.InjectDatabaseByToken = InjectDatabaseByToken;
39
+ //# sourceMappingURL=database.decorators.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.decorators.js","sourceRoot":"","sources":["../../src/middleware/database.decorators.ts"],"names":[],"mappings":";AAAA,wCAAwC;;;AAExC,2CAAwC;AACxC,qEAA8D;AAE9D;;;;;;;;;;GAUG;AACI,MAAM,cAAc,GAAG,GAAuB,EAAE,CAAC,IAAA,eAAM,EAAC,mCAAc,CAAC,CAAC;AAAlE,QAAA,cAAc,kBAAoD;AAE/E;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,qBAAqB,GAAG,CAAC,KAAa,EAAsB,EAAE,CAAC,IAAA,eAAM,EAAC,KAAK,CAAC,CAAC;AAA7E,QAAA,qBAAqB,yBAAwD"}
@@ -0,0 +1,99 @@
1
+ import { OnModuleDestroy } from '@nestjs/common';
2
+ import { DatabaseConfig, MongoRepositoryOptions, PostgresEntityConfig, Repository } from '../contracts/database.contracts';
3
+ import { MongoAdapter } from '../adapters/mongo.adapter';
4
+ import { PostgresAdapter } from '../adapters/postgres.adapter';
5
+ /**
6
+ * Main database service that provides a unified interface
7
+ * for database operations across MongoDB and PostgreSQL.
8
+ *
9
+ * This service acts as a facade over the underlying adapters,
10
+ * providing a clean API for creating repositories and managing connections.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * // In a NestJS service
15
+ * @Injectable()
16
+ * export class UserService {
17
+ * private readonly usersRepo: Repository<User>;
18
+ *
19
+ * constructor(@InjectDatabase() private readonly db: DatabaseService) {
20
+ * this.usersRepo = db.createMongoRepository({ model: UserModel });
21
+ * }
22
+ * }
23
+ * ```
24
+ */
25
+ export declare class DatabaseService implements OnModuleDestroy {
26
+ private readonly logger;
27
+ private readonly config;
28
+ private mongoAdapter?;
29
+ private postgresAdapter?;
30
+ constructor(config: DatabaseConfig);
31
+ /**
32
+ * Lifecycle hook called when the module is being destroyed.
33
+ * Gracefully closes all database connections.
34
+ */
35
+ onModuleDestroy(): Promise<void>;
36
+ /**
37
+ * Returns the current database type.
38
+ */
39
+ get type(): 'mongo' | 'postgres';
40
+ /**
41
+ * Checks if the database is connected.
42
+ */
43
+ isConnected(): boolean;
44
+ /**
45
+ * Initializes the underlying driver connection.
46
+ * Must be awaited before using repositories.
47
+ */
48
+ connect(): Promise<void>;
49
+ /**
50
+ * Gracefully disconnects from the database.
51
+ */
52
+ disconnect(): Promise<void>;
53
+ /**
54
+ * Creates a MongoDB repository using a Mongoose model.
55
+ *
56
+ * @param options - Options containing the Mongoose model
57
+ * @returns Repository instance with CRUD methods
58
+ * @throws Error if database type is not 'mongo'
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * const usersRepo = db.createMongoRepository<User>({ model: UserModel });
63
+ * const user = await usersRepo.create({ name: 'John' });
64
+ * ```
65
+ */
66
+ createMongoRepository<T = unknown>(options: MongoRepositoryOptions): Repository<T>;
67
+ /**
68
+ * Creates a PostgreSQL repository using a table configuration.
69
+ *
70
+ * @param cfg - Configuration for the entity/table
71
+ * @returns Repository instance with CRUD methods
72
+ * @throws Error if database type is not 'postgres'
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * const ordersRepo = db.createPostgresRepository<Order>({
77
+ * table: 'orders',
78
+ * primaryKey: 'id',
79
+ * columns: ['id', 'user_id', 'total', 'created_at'],
80
+ * });
81
+ * ```
82
+ */
83
+ createPostgresRepository<T = unknown>(cfg: PostgresEntityConfig): Repository<T>;
84
+ /**
85
+ * Returns the underlying MongoDB adapter.
86
+ * Useful for advanced operations not covered by the repository interface.
87
+ *
88
+ * @throws Error if database type is not 'mongo'
89
+ */
90
+ getMongoAdapter(): MongoAdapter;
91
+ /**
92
+ * Returns the underlying PostgreSQL adapter.
93
+ * Useful for advanced operations not covered by the repository interface.
94
+ *
95
+ * @throws Error if database type is not 'postgres'
96
+ */
97
+ getPostgresAdapter(): PostgresAdapter;
98
+ }
99
+ //# sourceMappingURL=database.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.service.d.ts","sourceRoot":"","sources":["../../src/services/database.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAsB,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EACH,cAAc,EAGd,sBAAsB,EACtB,oBAAoB,EACpB,UAAU,EACb,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAE/D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBACa,eAAgB,YAAW,eAAe;IACnD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAoC;IAC3D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;IAExC,OAAO,CAAC,YAAY,CAAC,CAAe;IACpC,OAAO,CAAC,eAAe,CAAC,CAAkB;gBAE9B,MAAM,EAAE,cAAc;IAKlC;;;OAGG;IACG,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAKtC;;OAEG;IACH,IAAI,IAAI,IAAI,OAAO,GAAG,UAAU,CAE/B;IAED;;OAEG;IACH,WAAW,IAAI,OAAO;IAWtB;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA4B9B;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAmBjC;;;;;;;;;;;;OAYG;IACH,qBAAqB,CAAC,CAAC,GAAG,OAAO,EAAE,OAAO,EAAE,sBAAsB,GAAG,UAAU,CAAC,CAAC,CAAC;IAclF;;;;;;;;;;;;;;;OAeG;IACH,wBAAwB,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,oBAAoB,GAAG,UAAU,CAAC,CAAC,CAAC;IAe/E;;;;;OAKG;IACH,eAAe,IAAI,YAAY;IAY/B;;;;;OAKG;IACH,kBAAkB,IAAI,eAAe;CAWxC"}