@lyxa.ai/core 1.0.58 → 1.0.61
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.
- package/dist/libraries/mongo/models/brand.model.js +2 -2
- package/dist/libraries/mongo/models/brand.model.js.map +1 -1
- package/dist/libraries/mongo/models/tag.model.d.ts +2 -2
- package/dist/libraries/mongo/models/tag.model.js +2 -2
- package/dist/libraries/mongo/models/tag.model.js.map +1 -1
- package/dist/utilities/error-handler.js +1 -1
- package/dist/utilities/error-handler.js.map +1 -1
- package/dist/utilities/validation/global-validation.d.ts +22 -54
- package/dist/utilities/validation/global-validation.js +6 -5
- package/dist/utilities/validation/global-validation.js.map +1 -1
- package/package.json +1 -1
|
@@ -18,11 +18,11 @@ let Brand = class Brand extends defaultClasses_1.TimeStamps {
|
|
|
18
18
|
};
|
|
19
19
|
exports.Brand = Brand;
|
|
20
20
|
__decorate([
|
|
21
|
-
(0, typegoose_1.prop)({ required: true, type: String }),
|
|
21
|
+
(0, typegoose_1.prop)({ required: true, type: String, trim: true, maxlength: 50 }),
|
|
22
22
|
__metadata("design:type", String)
|
|
23
23
|
], Brand.prototype, "name", void 0);
|
|
24
24
|
__decorate([
|
|
25
|
-
(0, typegoose_1.prop)({ type: String }),
|
|
25
|
+
(0, typegoose_1.prop)({ type: String, maxlength: 250 }),
|
|
26
26
|
__metadata("design:type", String)
|
|
27
27
|
], Brand.prototype, "description", void 0);
|
|
28
28
|
exports.Brand = Brand = __decorate([
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"brand.model.js","sourceRoot":"/","sources":["libraries/mongo/models/brand.model.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAAiE;AACjE,4EAAqE;AAI9D,IAAM,KAAK,GAAX,MAAM,KAAM,SAAQ,2BAAU;IAE7B,IAAI,CAAU;IAGd,WAAW,CAAU;CAC5B,CAAA;AANY,sBAAK;AAEV;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;;
|
|
1
|
+
{"version":3,"file":"brand.model.js","sourceRoot":"/","sources":["libraries/mongo/models/brand.model.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAAiE;AACjE,4EAAqE;AAI9D,IAAM,KAAK,GAAX,MAAM,KAAM,SAAQ,2BAAU;IAE7B,IAAI,CAAU;IAGd,WAAW,CAAU;CAC5B,CAAA;AANY,sBAAK;AAEV;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;;mCAC7C;AAGd;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;;0CACX;gBALhB,KAAK;IAFjB,IAAA,wBAAY,EAAC,EAAE,aAAa,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,EAAE,CAAC;IACzD,IAAA,iBAAK,EAAC,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,uBAAuB,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC;GACtE,KAAK,CAMjB","sourcesContent":["import { Index, modelOptions, prop } from '@typegoose/typegoose';\nimport { TimeStamps } from '@typegoose/typegoose/lib/defaultClasses';\n\n@modelOptions({ schemaOptions: { collection: 'brands' } })\n@Index({ name: 1 }, { unique: true, partialFilterExpression: { deletedAt: null } })\nexport class Brand extends TimeStamps {\n\t@prop({ required: true, type: String, trim: true, maxlength: 50 })\n\tpublic name!: string;\n\n\t@prop({ type: String, maxlength: 250 })\n\tpublic description?: string;\n}\n"]}
|
|
@@ -23,11 +23,11 @@ let Tag = class Tag {
|
|
|
23
23
|
};
|
|
24
24
|
exports.Tag = Tag;
|
|
25
25
|
__decorate([
|
|
26
|
-
(0, typegoose_1.prop)({ required: true, type: String }),
|
|
26
|
+
(0, typegoose_1.prop)({ required: true, type: String, trim: true, maxlength: 30 }),
|
|
27
27
|
__metadata("design:type", String)
|
|
28
28
|
], Tag.prototype, "name", void 0);
|
|
29
29
|
__decorate([
|
|
30
|
-
(0, typegoose_1.prop)({ type: String }),
|
|
30
|
+
(0, typegoose_1.prop)({ required: true, type: String }),
|
|
31
31
|
__metadata("design:type", String)
|
|
32
32
|
], Tag.prototype, "image", void 0);
|
|
33
33
|
__decorate([
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tag.model.js","sourceRoot":"/","sources":["libraries/mongo/models/tag.model.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAAsE;AACtE,kDAA2D;AAC3D,wBAA6B;AAsGtB,IAAM,GAAG,GAAT,MAAM,GAAG;IAER,IAAI,CAAU;IAGd,KAAK,CAAU;IAGf,QAAQ,CAAY;IAGpB,MAAM,CAAU;IAGhB,SAAS,CAAW;IAGpB,YAAY,CAAU;CAC7B,CAAA;AAlBY,kBAAG;AAER;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;;
|
|
1
|
+
{"version":3,"file":"tag.model.js","sourceRoot":"/","sources":["libraries/mongo/models/tag.model.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAAsE;AACtE,kDAA2D;AAC3D,wBAA6B;AAsGtB,IAAM,GAAG,GAAT,MAAM,GAAG;IAER,IAAI,CAAU;IAGd,KAAK,CAAU;IAGf,QAAQ,CAAY;IAGpB,MAAM,CAAU;IAGhB,SAAS,CAAW;IAGpB,YAAY,CAAU;CAC7B,CAAA;AAlBY,kBAAG;AAER;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;;iCAC7C;AAGd;IADN,IAAA,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,CAAC;YACF,CAAC;QACF,CAAC;QAED,IAAI,EAAE,CAAC;IACR,CAAC,CAAC;IACD,IAAA,eAAG,EAAM,kBAAkB,EAAE,KAAK,WAAkC,IAAI;QACxE,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAS,CAAC;QAEvC,IAAI,MAAM,EAAE,MAAM,KAAK,aAAM,CAAC,MAAM,EAAE,CAAC;YAEtC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;YAEtD,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,aAAM,CAAC,MAAM,EAAE,CAAC;gBAEzC,MAAM,eAAe,GAAG,MAAM,WAAQ,CAAC,SAAS,CAA8B;oBAC7E;wBACC,MAAM,EAAE;4BACP,QAAQ,EAAE,GAAG,CAAC,QAAQ;4BACtB,MAAM,EAAE,aAAM,CAAC,MAAM;4BACrB,SAAS,EAAE,IAAI;yBACf;qBACD;oBACD;wBACC,MAAM,EAAE;4BACP,GAAG,EAAE,IAAI;4BACT,eAAe,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE;yBAC1C;qBACD;iBACD,CAAC,CAAC,IAAI,EAAE,CAAC;gBAGV,MAAM,CAAC,YAAY,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,eAAe,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;gBAGtE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;YACxB,CAAC;QACF,CAAC;QAED,IAAI,EAAE,CAAC;IACR,CAAC,CAAC;GACW,GAAG,CAkBf","sourcesContent":["import { Index, modelOptions, pre, prop } from '@typegoose/typegoose';\nimport { ItemType, Status } from '../../../utilities/enum';\nimport { TagModel } from '.';\nimport { Query } from 'mongoose';\n\n@modelOptions({ schemaOptions: { collection: 'tags' } })\n@Index({ name: 1, itemType: 1 }, { unique: true, partialFilterExpression: { deletedAt: null } })\n@Index({ itemType: 1, deletedAt: 1 })\n@pre<Tag>('save', async function (next) {\n\t// Only set sortingOrder if it's a new document or sortingOrder is not set\n\tif (this.isNew || typeof this.sortingOrder === 'undefined') {\n\t\ttry {\n\t\t\t// Find the maximum sortingOrder for tags with the same itemType that aren't deleted\n\t\t\tconst maxSortingOrder = await TagModel.aggregate<{ maxSortingOrder: number }>([\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\titemType: this.itemType,\n\t\t\t\t\t\tstatus: Status.ACTIVE,\n\t\t\t\t\t\tdeletedAt: null,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: null,\n\t\t\t\t\t\tmaxSortingOrder: { $max: '$sortingOrder' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]).exec();\n\n\t\t\t// Set the new sortingOrder to max + 1 (or 0 if no items found)\n\t\t\tthis.sortingOrder = (maxSortingOrder[0]?.maxSortingOrder ?? -1) + 1;\n\t\t} catch (error) {\n\t\t\treturn next(error as Error);\n\t\t}\n\t}\n\n\t// Add this code to handle status change from inactive to active\n\tif (this.isModified('status') && this.status === Status.ACTIVE) {\n\t\t// Check if status was previously inactive\n\t\tconst original = await TagModel.findById(this._id);\n\t\tif (original && original.status !== Status.ACTIVE) {\n\t\t\ttry {\n\t\t\t\t// Find the maximum sortingOrder for active tags with the same itemType\n\t\t\t\tconst maxSortingOrder = await TagModel.aggregate<{ maxSortingOrder: number }>([\n\t\t\t\t\t{\n\t\t\t\t\t\t$match: {\n\t\t\t\t\t\t\titemType: this.itemType,\n\t\t\t\t\t\t\tstatus: Status.ACTIVE,\n\t\t\t\t\t\t\tdeletedAt: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$group: {\n\t\t\t\t\t\t\t_id: null,\n\t\t\t\t\t\t\tmaxSortingOrder: { $max: '$sortingOrder' },\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t]).exec();\n\n\t\t\t\t// Set the sortingOrder to max + 1 (or 0 if no items found)\n\t\t\t\tthis.sortingOrder = (maxSortingOrder[0]?.maxSortingOrder ?? -1) + 1;\n\t\t\t} catch (error) {\n\t\t\t\treturn next(error as Error);\n\t\t\t}\n\t\t}\n\t}\n\n\tnext();\n})\n@pre<Tag>('findOneAndUpdate', async function (this: Query<any, Tag>, next) {\n\tconst update = this.getUpdate() as any;\n\n\tif (update?.status === Status.ACTIVE) {\n\t\t// Get current document (before update)\n\t\tconst tag = await this.model.findOne(this.getQuery());\n\n\t\tif (tag && tag.status !== Status.ACTIVE) {\n\t\t\t// Find the maximum sortingOrder for active tags with the same itemType\n\t\t\tconst maxSortingOrder = await TagModel.aggregate<{ maxSortingOrder: number }>([\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\titemType: tag.itemType,\n\t\t\t\t\t\tstatus: Status.ACTIVE,\n\t\t\t\t\t\tdeletedAt: null,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: null,\n\t\t\t\t\t\tmaxSortingOrder: { $max: '$sortingOrder' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]).exec();\n\n\t\t\t// Set the sortingOrder to max + 1 (or 0 if no items found)\n\t\t\tupdate.sortingOrder = (maxSortingOrder[0]?.maxSortingOrder ?? -1) + 1;\n\n\t\t\t// Inject the new sortingOrder into the update\n\t\t\tthis.setUpdate(update);\n\t\t}\n\t}\n\n\tnext();\n})\nexport class Tag {\n\t@prop({ required: true, type: String, trim: true, maxlength: 30 })\n\tpublic name!: string;\n\n\t@prop({ required: true, type: String })\n\tpublic image!: string;\n\n\t@prop({ required: true, type: String, enum: ItemType })\n\tpublic itemType!: ItemType;\n\n\t@prop({ type: String, enum: Status, default: Status.ACTIVE })\n\tpublic status?: Status;\n\n\t@prop({ type: Boolean, default: true })\n\tpublic isVisible?: boolean;\n\n\t@prop({ type: Number })\n\tpublic sortingOrder?: number;\n}\n"]}
|
|
@@ -11,7 +11,7 @@ class ErrorHandler {
|
|
|
11
11
|
retryableErrors: new Set(['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE']),
|
|
12
12
|
};
|
|
13
13
|
static MONGO_ERROR_CODES = {
|
|
14
|
-
11000: { code: 'CONFLICT', message: '
|
|
14
|
+
11000: { code: 'CONFLICT', message: 'A record with this value already exists.' },
|
|
15
15
|
11001: { code: 'CONFLICT', message: 'Duplicate key error on index update.' },
|
|
16
16
|
121: { code: 'BAD_REQUEST', message: 'Document validation failed.' },
|
|
17
17
|
7: { code: 'INTERNAL_SERVER_ERROR', message: 'Not primary - database is in recovery mode.' },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.js","sourceRoot":"/","sources":["utilities/error-handler.ts"],"names":[],"mappings":";;;AAKA,yCAAyC;AACzC,qCAA0E;AAC1E,6BAA+B;AAM/B,MAAa,YAAY;IAKhB,MAAM,CAAU,MAAM,GAAG;QAEhC,eAAe,EAAE,IAAI;QAErB,kBAAkB,EAAE,EAAE;QAEtB,eAAe,EAAE,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,cAAc,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;KAC9E,CAAC;IAMM,MAAM,CAAU,iBAAiB,GAMrC;QACH,KAAK,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,+DAA+D,EAAE;QACrG,KAAK,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,sCAAsC,EAAE;QAC5E,GAAG,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,6BAA6B,EAAE;QACpE,CAAC,EAAE,EAAE,IAAI,EAAE,uBAAuB,EAAE,OAAO,EAAE,6CAA6C,EAAE;QAC5F,EAAE,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,mCAAmC,EA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;gBACzB,aAAa,EAAE,KAAK;gBACpB,OAAO,EAAE;oBACR,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,WAAW,EAAE,IAAI;iBACjB;aACD,CAAC;QACH,CAAC;QAED,IAAI,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO;gBACN,IAAI,EAAE,YAAY;gBAClB,aAAa,EAAE,KAAK;gBACpB,OAAO,EAAE;oBACR,IAAI,EAAG,KAA0B,CAAC,IAAI;oBACtC,QAAQ,EAAG,KAA0B,CAAC,QAAQ;oBAC9C,UAAU,EAAG,KAA0B,CAAC,UAAU;iBAClD;aACD,CAAC;QACH,CAAC;QAED,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;YAC5B,OAAO;gBACN,IAAI,EAAE,WAAW;gBACjB,aAAa,EAAE,KAAK;gBACpB,OAAO,EAAE;oBACR,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,IAAI,EAAG,KAA+B,CAAC,IAAI;iBAC3C;aACD,CAAC;QACH,CAAC;QAED,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC;IACvD,CAAC;;AAtUF,oCAuUC","sourcesContent":["/**\n * @fileoverview Error handling utility for TRPC and MongoDB operations.\n * Provides centralized error handling, logging, and retry mechanisms.\n */\n\nimport { TRPCError } from '@trpc/server';\nimport { MongoServerError, MongoError, MongoNetworkError } from 'mongodb';\nimport { ZodError } from 'zod';\n\n/**\n * A utility class for handling various types of errors in a TRPC-MongoDB application.\n * Provides error transformation, logging, and retry mechanisms.\n */\nexport class ErrorHandler {\n\t/**\n\t * Configuration options for error handling behavior\n\t * @private\n\t */\n\tprivate static readonly CONFIG = {\n\t\t/** Whether to log errors to console */\n\t\tshouldLogErrors: true,\n\t\t/** Maximum number of stack trace lines to include in logs */\n\t\tmaxStackTraceLines: 10,\n\t\t/** Set of error codes that are considered retryable */\n\t\tretryableErrors: new Set(['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE']),\n\t};\n\n\t/**\n\t * Mapping of MongoDB error codes to TRPC error types and messages\n\t * @private\n\t */\n\tprivate static readonly MONGO_ERROR_CODES: Record<\n\t\tnumber,\n\t\t{\n\t\t\tcode: TRPCError['code'];\n\t\t\tmessage: string;\n\t\t}\n\t> = {\n\t\t11000: { code: 'CONFLICT', message: 'Duplicate key error: A record with this value already exists.' },\n\t\t11001: { code: 'CONFLICT', message: 'Duplicate key error on index update.' },\n\t\t121: { code: 'BAD_REQUEST', message: 'Document validation failed.' },\n\t\t7: { code: 'INTERNAL_SERVER_ERROR', message: 'Not primary - database is in recovery mode.' },\n\t\t89: { code: 'FORBIDDEN', message: 'Unauthorized operation attempted.' },\n\t\t91: { code: 'TIMEOUT', message: 'Operation timeout exceeded.' },\n\t\t189: { code: 'BAD_REQUEST', message: 'Invalid modification - document would exceed size limit.' },\n\t\t50: { code: 'INTERNAL_SERVER_ERROR', message: 'Database execution error.' },\n\t};\n\n\t/**\n\t * Logs error information with metadata and stack trace\n\t * @private\n\t * @param error - The error to log\n\t * @param context - Additional context information for the error\n\t */\n\tprivate static logError(error: unknown, context: Record<string, unknown> = {}): void {\n\t\tif (!this.CONFIG.shouldLogErrors) return;\n\n\t\tconst errorMeta = this.extractErrorMetadata(error);\n\t\tconst timestamp = new Date().toISOString();\n\n\t\tconst logData = {\n\t\t\ttimestamp,\n\t\t\ttype: errorMeta.type,\n\t\t\tmessage: error instanceof Error ? error.message : 'Unknown error',\n\t\t\tstack:\n\t\t\t\terror instanceof Error\n\t\t\t\t\t? error.stack?.split('\\n').slice(0, this.CONFIG.maxStackTraceLines).join('\\n')\n\t\t\t\t\t: undefined,\n\t\t\tcontext,\n\t\t\tmetadata: errorMeta,\n\t\t};\n\n\t\tconsole.error('[ErrorHandler]:', JSON.stringify(logData, null, 2));\n\t}\n\n\t/**\n\t * Main error handling method that transforms various error types into TRPC errors\n\t * @param error - The error to handle\n\t * @param customMessage - Optional custom error message\n\t * @param context - Additional context information\n\t * @throws {TRPCError} Transformed error with appropriate error code and message\n\t */\n\tpublic static handleError(\n\t\terror: unknown,\n\t\tcustomMessage = 'An unexpected error occurred',\n\t\tcontext: Record<string, unknown> = {}\n\t): never {\n\t\tthis.logError(error, context);\n\n\t\tif (error instanceof TRPCError) {\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (error instanceof ZodError) {\n\t\t\ttry {\n\t\t\t\tconsole.log('ZodError:', error.flatten());\n\t\t\t\tconst formatted = error.errors.map(e => ({\n\t\t\t\t\tfield: e.path.join('.'),\n\t\t\t\t\tmessage: e.message,\n\t\t\t\t}));\n\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\t\tmessage: 'Validation error',\n\t\t\t\t\tcause: formatted,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\t// Handle any issues with flattening or logging\n\t\t\t\tconsole.error('Error while processing ZodError:', err);\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\t\tmessage: 'Error processing validation error',\n\t\t\t\t\tcause: err,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (error instanceof MongoNetworkError) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Database connection error',\n\t\t\t\tcause: error,\n\t\t\t});\n\t\t}\n\n\t\tif (this.isMongoError(error)) {\n\t\t\tthrow this.createMongoTRPCError(error);\n\t\t}\n\n\t\tif (error instanceof Error) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: this.mapNodeErrorCode(error),\n\t\t\t\tmessage: error.message || customMessage,\n\t\t\t\tcause: error,\n\t\t\t});\n\t\t}\n\n\t\tthrow new TRPCError({\n\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\tmessage: customMessage,\n\t\t\tcause: error,\n\t\t});\n\t}\n\n\t/**\n\t * Type guard to check if an error is a MongoDB error\n\t * @private\n\t * @param error - The error to check\n\t * @returns True if the error is a MongoDB error\n\t */\n\tprivate static isMongoError(error: unknown): error is MongoServerError {\n\t\treturn (\n\t\t\terror instanceof MongoServerError ||\n\t\t\terror instanceof MongoError ||\n\t\t\t(typeof error === 'object' &&\n\t\t\t\terror !== null &&\n\t\t\t\t'code' in error &&\n\t\t\t\t'name' in error &&\n\t\t\t\t((error as MongoServerError).name === 'MongoServerError' ||\n\t\t\t\t\t(error as MongoServerError).name === 'MongoError'))\n\t\t);\n\t}\n\n\t/**\n\t * Creates a TRPC error from a MongoDB error\n\t * @private\n\t * @param error - MongoDB error to transform\n\t * @returns Transformed TRPC error\n\t */\n\tprivate static createMongoTRPCError(error: MongoServerError): TRPCError {\n\t\tconst errorCode = typeof error.code === 'number' ? error.code : 0;\n\t\tconst errorInfo = this.MONGO_ERROR_CODES[errorCode] || {\n\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\tmessage: `Database error occurred. Code: ${errorCode}`,\n\t\t};\n\n\t\treturn new TRPCError({\n\t\t\tcode: errorInfo.code,\n\t\t\tmessage: errorInfo.message,\n\t\t\tcause: error,\n\t\t});\n\t}\n\n\t/**\n\t * Maps Node.js error codes to TRPC error codes\n\t * @private\n\t * @param error - Node.js error to map\n\t * @returns Appropriate TRPC error code\n\t */\n\tprivate static mapNodeErrorCode(error: Error): TRPCError['code'] {\n\t\tconst nodeErrorMap: Record<string, TRPCError['code']> = {\n\t\t\tENOENT: 'NOT_FOUND',\n\t\t\tEACCES: 'FORBIDDEN',\n\t\t\tECONNREFUSED: 'INTERNAL_SERVER_ERROR',\n\t\t\tECONNRESET: 'INTERNAL_SERVER_ERROR',\n\t\t\tETIMEDOUT: 'TIMEOUT',\n\t\t\tEPIPE: 'INTERNAL_SERVER_ERROR',\n\t\t\tENOTFOUND: 'NOT_FOUND',\n\t\t\tEINVAL: 'BAD_REQUEST',\n\t\t\tEMFILE: 'INTERNAL_SERVER_ERROR',\n\t\t\tEPERM: 'FORBIDDEN',\n\t\t};\n\n\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\treturn code ? nodeErrorMap[code] || 'INTERNAL_SERVER_ERROR' : 'INTERNAL_SERVER_ERROR';\n\t}\n\n\t/**\n\t * Wraps an async function with error handling\n\t * @param fn - Async function to wrap\n\t * @param context - Additional context information\n\t * @returns Promise resolving to the function's return type\n\t * @throws {TRPCError} If the function throws an error\n\t */\n\tpublic static async wrapAsync<T>(fn: () => Promise<T>, context: Record<string, unknown> = {}): Promise<T> {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} catch (error) {\n\t\t\tthis.handleError(error, undefined, context);\n\t\t}\n\t}\n\n\t/**\n\t * Executes an async function with retry mechanism for transient errors\n\t * @param fn - Async function to execute\n\t * @param options - Retry configuration options\n\t * @returns Promise resolving to the function's return type\n\t * @throws {TRPCError} If all retry attempts fail\n\t */\n\tpublic static async withRetry<T>(\n\t\tfn: () => Promise<T>,\n\t\toptions: {\n\t\t\tmaxAttempts?: number;\n\t\t\tdelayMs?: number;\n\t\t\tbackoffFactor?: number;\n\t\t\tcontext?: Record<string, unknown>;\n\t\t} = {}\n\t): Promise<T> {\n\t\tconst { maxAttempts = 3, delayMs = 1000, backoffFactor = 2, context = {} } = options;\n\n\t\tlet lastError: unknown;\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn await fn();\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error;\n\n\t\t\t\tconst isRetryable = this.isRetryableError(error);\n\t\t\t\tconst isLastAttempt = attempt === maxAttempts;\n\n\t\t\t\tif (!isRetryable || isLastAttempt) {\n\t\t\t\t\tthis.handleError(error, undefined, { ...context, attempt });\n\t\t\t\t}\n\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, delayMs * Math.pow(backoffFactor, attempt - 1)));\n\t\t\t}\n\t\t}\n\n\t\tthrow lastError;\n\t}\n\n\t/**\n\t * Determines if an error is retryable\n\t * @private\n\t * @param error - The error to check\n\t * @returns True if the error is retryable\n\t */\n\tprivate static isRetryableError(error: unknown): boolean {\n\t\tif (error instanceof MongoNetworkError) return true;\n\t\tif (error instanceof Error) {\n\t\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\t\treturn code ? this.CONFIG.retryableErrors.has(code) : false;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Extracts metadata from an error for logging and analysis\n\t * @param error - The error to extract metadata from\n\t * @returns Object containing error type, original error, and additional details\n\t */\n\tpublic static extractErrorMetadata(error: unknown): {\n\t\ttype: string;\n\t\toriginalError: unknown;\n\t\tdetails?: Record<string, unknown>;\n\t} {\n\t\tif (error instanceof TRPCError) {\n\t\t\treturn {\n\t\t\t\ttype: 'TRPCError',\n\t\t\t\toriginalError: error.cause ?? error,\n\t\t\t\tdetails: {\n\t\t\t\t\tcode: error.code,\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (error instanceof ZodError) {\n\t\t\treturn {\n\t\t\t\ttype: 'ZodError',\n\t\t\t\toriginalError: error,\n\t\t\t\tdetails: error.flatten(),\n\t\t\t};\n\t\t}\n\n\t\tif (error instanceof MongoNetworkError) {\n\t\t\treturn {\n\t\t\t\ttype: 'MongoNetworkError',\n\t\t\t\toriginalError: error,\n\t\t\t\tdetails: {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tisRetryable: true,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (this.isMongoError(error)) {\n\t\t\treturn {\n\t\t\t\ttype: 'MongoError',\n\t\t\t\toriginalError: error,\n\t\t\t\tdetails: {\n\t\t\t\t\tcode: (error as MongoServerError).code,\n\t\t\t\t\tcodeName: (error as MongoServerError).codeName,\n\t\t\t\t\tkeyPattern: (error as MongoServerError).keyPattern,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (error instanceof Error) {\n\t\t\treturn {\n\t\t\t\ttype: 'NodeError',\n\t\t\t\toriginalError: error,\n\t\t\t\tdetails: {\n\t\t\t\t\tname: error.name,\n\t\t\t\t\tcode: (error as NodeJS.ErrnoException).code,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\treturn { type: 'UnknownError', originalError: error };\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.js","sourceRoot":"/","sources":["utilities/error-handler.ts"],"names":[],"mappings":";;;AAKA,yCAAyC;AACzC,qCAA0E;AAC1E,6BAA+B;AAM/B,MAAa,YAAY;IAKhB,MAAM,CAAU,MAAM,GAAG;QAEhC,eAAe,EAAE,IAAI;QAErB,kBAAkB,EAAE,EAAE;QAEtB,eAAe,EAAE,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,cAAc,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;KAC9E,CAAC;IAMM,MAAM,CAAU,iBAAiB,GAMrC;QACH,KAAK,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,0CAA0C,EAAE;QAChF,KAAK,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,sCAAsC,EAAE;QAC5E,GAAG,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,6BAA6B,EAAE;QACpE,CAAC,EAAE,EAAE,IAAI,EAAE,uBAAuB,EAAE,OAAO,EAAE,6CAA6C,EAAE;QAC5F,EAAE,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,mCAAmC,EAAE;QACvE,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,6BAA6B,EAAE;QAC/D,GAAG,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,0DAA0D,EAAE;QACjG,EAAE,EAAE,EAAE,IAAI,EAAE,uBAAuB,EAAE,OAAO,EAAE,2BAA2B,EAAE;KAC3E,CAAC;IAQM,MAAM,CAAC,QAAQ,CAAC,KAAc,EAAE,UAAmC,EAAE;QAC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AC,IAAI;oBACtC,QAAQ,EAAG,KAA0B,CAAC,QAAQ;oBAC9C,UAAU,EAAG,KAA0B,CAAC,UAAU;iBAClD;aACD,CAAC;QACH,CAAC;QAED,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;YAC5B,OAAO;gBACN,IAAI,EAAE,WAAW;gBACjB,aAAa,EAAE,KAAK;gBACpB,OAAO,EAAE;oBACR,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,IAAI,EAAG,KAA+B,CAAC,IAAI;iBAC3C;aACD,CAAC;QACH,CAAC;QAED,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC;IACvD,CAAC;;AAtUF,oCAuUC","sourcesContent":["/**\n * @fileoverview Error handling utility for TRPC and MongoDB operations.\n * Provides centralized error handling, logging, and retry mechanisms.\n */\n\nimport { TRPCError } from '@trpc/server';\nimport { MongoServerError, MongoError, MongoNetworkError } from 'mongodb';\nimport { ZodError } from 'zod';\n\n/**\n * A utility class for handling various types of errors in a TRPC-MongoDB application.\n * Provides error transformation, logging, and retry mechanisms.\n */\nexport class ErrorHandler {\n\t/**\n\t * Configuration options for error handling behavior\n\t * @private\n\t */\n\tprivate static readonly CONFIG = {\n\t\t/** Whether to log errors to console */\n\t\tshouldLogErrors: true,\n\t\t/** Maximum number of stack trace lines to include in logs */\n\t\tmaxStackTraceLines: 10,\n\t\t/** Set of error codes that are considered retryable */\n\t\tretryableErrors: new Set(['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE']),\n\t};\n\n\t/**\n\t * Mapping of MongoDB error codes to TRPC error types and messages\n\t * @private\n\t */\n\tprivate static readonly MONGO_ERROR_CODES: Record<\n\t\tnumber,\n\t\t{\n\t\t\tcode: TRPCError['code'];\n\t\t\tmessage: string;\n\t\t}\n\t> = {\n\t\t11000: { code: 'CONFLICT', message: 'A record with this value already exists.' },\n\t\t11001: { code: 'CONFLICT', message: 'Duplicate key error on index update.' },\n\t\t121: { code: 'BAD_REQUEST', message: 'Document validation failed.' },\n\t\t7: { code: 'INTERNAL_SERVER_ERROR', message: 'Not primary - database is in recovery mode.' },\n\t\t89: { code: 'FORBIDDEN', message: 'Unauthorized operation attempted.' },\n\t\t91: { code: 'TIMEOUT', message: 'Operation timeout exceeded.' },\n\t\t189: { code: 'BAD_REQUEST', message: 'Invalid modification - document would exceed size limit.' },\n\t\t50: { code: 'INTERNAL_SERVER_ERROR', message: 'Database execution error.' },\n\t};\n\n\t/**\n\t * Logs error information with metadata and stack trace\n\t * @private\n\t * @param error - The error to log\n\t * @param context - Additional context information for the error\n\t */\n\tprivate static logError(error: unknown, context: Record<string, unknown> = {}): void {\n\t\tif (!this.CONFIG.shouldLogErrors) return;\n\n\t\tconst errorMeta = this.extractErrorMetadata(error);\n\t\tconst timestamp = new Date().toISOString();\n\n\t\tconst logData = {\n\t\t\ttimestamp,\n\t\t\ttype: errorMeta.type,\n\t\t\tmessage: error instanceof Error ? error.message : 'Unknown error',\n\t\t\tstack:\n\t\t\t\terror instanceof Error\n\t\t\t\t\t? error.stack?.split('\\n').slice(0, this.CONFIG.maxStackTraceLines).join('\\n')\n\t\t\t\t\t: undefined,\n\t\t\tcontext,\n\t\t\tmetadata: errorMeta,\n\t\t};\n\n\t\tconsole.error('[ErrorHandler]:', JSON.stringify(logData, null, 2));\n\t}\n\n\t/**\n\t * Main error handling method that transforms various error types into TRPC errors\n\t * @param error - The error to handle\n\t * @param customMessage - Optional custom error message\n\t * @param context - Additional context information\n\t * @throws {TRPCError} Transformed error with appropriate error code and message\n\t */\n\tpublic static handleError(\n\t\terror: unknown,\n\t\tcustomMessage = 'An unexpected error occurred',\n\t\tcontext: Record<string, unknown> = {}\n\t): never {\n\t\tthis.logError(error, context);\n\n\t\tif (error instanceof TRPCError) {\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (error instanceof ZodError) {\n\t\t\ttry {\n\t\t\t\tconsole.log('ZodError:', error.flatten());\n\t\t\t\tconst formatted = error.errors.map(e => ({\n\t\t\t\t\tfield: e.path.join('.'),\n\t\t\t\t\tmessage: e.message,\n\t\t\t\t}));\n\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'BAD_REQUEST',\n\t\t\t\t\tmessage: 'Validation error',\n\t\t\t\t\tcause: formatted,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\t// Handle any issues with flattening or logging\n\t\t\t\tconsole.error('Error while processing ZodError:', err);\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\t\tmessage: 'Error processing validation error',\n\t\t\t\t\tcause: err,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (error instanceof MongoNetworkError) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Database connection error',\n\t\t\t\tcause: error,\n\t\t\t});\n\t\t}\n\n\t\tif (this.isMongoError(error)) {\n\t\t\tthrow this.createMongoTRPCError(error);\n\t\t}\n\n\t\tif (error instanceof Error) {\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: this.mapNodeErrorCode(error),\n\t\t\t\tmessage: error.message || customMessage,\n\t\t\t\tcause: error,\n\t\t\t});\n\t\t}\n\n\t\tthrow new TRPCError({\n\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\tmessage: customMessage,\n\t\t\tcause: error,\n\t\t});\n\t}\n\n\t/**\n\t * Type guard to check if an error is a MongoDB error\n\t * @private\n\t * @param error - The error to check\n\t * @returns True if the error is a MongoDB error\n\t */\n\tprivate static isMongoError(error: unknown): error is MongoServerError {\n\t\treturn (\n\t\t\terror instanceof MongoServerError ||\n\t\t\terror instanceof MongoError ||\n\t\t\t(typeof error === 'object' &&\n\t\t\t\terror !== null &&\n\t\t\t\t'code' in error &&\n\t\t\t\t'name' in error &&\n\t\t\t\t((error as MongoServerError).name === 'MongoServerError' ||\n\t\t\t\t\t(error as MongoServerError).name === 'MongoError'))\n\t\t);\n\t}\n\n\t/**\n\t * Creates a TRPC error from a MongoDB error\n\t * @private\n\t * @param error - MongoDB error to transform\n\t * @returns Transformed TRPC error\n\t */\n\tprivate static createMongoTRPCError(error: MongoServerError): TRPCError {\n\t\tconst errorCode = typeof error.code === 'number' ? error.code : 0;\n\t\tconst errorInfo = this.MONGO_ERROR_CODES[errorCode] || {\n\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\tmessage: `Database error occurred. Code: ${errorCode}`,\n\t\t};\n\n\t\treturn new TRPCError({\n\t\t\tcode: errorInfo.code,\n\t\t\tmessage: errorInfo.message,\n\t\t\tcause: error,\n\t\t});\n\t}\n\n\t/**\n\t * Maps Node.js error codes to TRPC error codes\n\t * @private\n\t * @param error - Node.js error to map\n\t * @returns Appropriate TRPC error code\n\t */\n\tprivate static mapNodeErrorCode(error: Error): TRPCError['code'] {\n\t\tconst nodeErrorMap: Record<string, TRPCError['code']> = {\n\t\t\tENOENT: 'NOT_FOUND',\n\t\t\tEACCES: 'FORBIDDEN',\n\t\t\tECONNREFUSED: 'INTERNAL_SERVER_ERROR',\n\t\t\tECONNRESET: 'INTERNAL_SERVER_ERROR',\n\t\t\tETIMEDOUT: 'TIMEOUT',\n\t\t\tEPIPE: 'INTERNAL_SERVER_ERROR',\n\t\t\tENOTFOUND: 'NOT_FOUND',\n\t\t\tEINVAL: 'BAD_REQUEST',\n\t\t\tEMFILE: 'INTERNAL_SERVER_ERROR',\n\t\t\tEPERM: 'FORBIDDEN',\n\t\t};\n\n\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\treturn code ? nodeErrorMap[code] || 'INTERNAL_SERVER_ERROR' : 'INTERNAL_SERVER_ERROR';\n\t}\n\n\t/**\n\t * Wraps an async function with error handling\n\t * @param fn - Async function to wrap\n\t * @param context - Additional context information\n\t * @returns Promise resolving to the function's return type\n\t * @throws {TRPCError} If the function throws an error\n\t */\n\tpublic static async wrapAsync<T>(fn: () => Promise<T>, context: Record<string, unknown> = {}): Promise<T> {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} catch (error) {\n\t\t\tthis.handleError(error, undefined, context);\n\t\t}\n\t}\n\n\t/**\n\t * Executes an async function with retry mechanism for transient errors\n\t * @param fn - Async function to execute\n\t * @param options - Retry configuration options\n\t * @returns Promise resolving to the function's return type\n\t * @throws {TRPCError} If all retry attempts fail\n\t */\n\tpublic static async withRetry<T>(\n\t\tfn: () => Promise<T>,\n\t\toptions: {\n\t\t\tmaxAttempts?: number;\n\t\t\tdelayMs?: number;\n\t\t\tbackoffFactor?: number;\n\t\t\tcontext?: Record<string, unknown>;\n\t\t} = {}\n\t): Promise<T> {\n\t\tconst { maxAttempts = 3, delayMs = 1000, backoffFactor = 2, context = {} } = options;\n\n\t\tlet lastError: unknown;\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn await fn();\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error;\n\n\t\t\t\tconst isRetryable = this.isRetryableError(error);\n\t\t\t\tconst isLastAttempt = attempt === maxAttempts;\n\n\t\t\t\tif (!isRetryable || isLastAttempt) {\n\t\t\t\t\tthis.handleError(error, undefined, { ...context, attempt });\n\t\t\t\t}\n\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, delayMs * Math.pow(backoffFactor, attempt - 1)));\n\t\t\t}\n\t\t}\n\n\t\tthrow lastError;\n\t}\n\n\t/**\n\t * Determines if an error is retryable\n\t * @private\n\t * @param error - The error to check\n\t * @returns True if the error is retryable\n\t */\n\tprivate static isRetryableError(error: unknown): boolean {\n\t\tif (error instanceof MongoNetworkError) return true;\n\t\tif (error instanceof Error) {\n\t\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\t\treturn code ? this.CONFIG.retryableErrors.has(code) : false;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Extracts metadata from an error for logging and analysis\n\t * @param error - The error to extract metadata from\n\t * @returns Object containing error type, original error, and additional details\n\t */\n\tpublic static extractErrorMetadata(error: unknown): {\n\t\ttype: string;\n\t\toriginalError: unknown;\n\t\tdetails?: Record<string, unknown>;\n\t} {\n\t\tif (error instanceof TRPCError) {\n\t\t\treturn {\n\t\t\t\ttype: 'TRPCError',\n\t\t\t\toriginalError: error.cause ?? error,\n\t\t\t\tdetails: {\n\t\t\t\t\tcode: error.code,\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (error instanceof ZodError) {\n\t\t\treturn {\n\t\t\t\ttype: 'ZodError',\n\t\t\t\toriginalError: error,\n\t\t\t\tdetails: error.flatten(),\n\t\t\t};\n\t\t}\n\n\t\tif (error instanceof MongoNetworkError) {\n\t\t\treturn {\n\t\t\t\ttype: 'MongoNetworkError',\n\t\t\t\toriginalError: error,\n\t\t\t\tdetails: {\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tisRetryable: true,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (this.isMongoError(error)) {\n\t\t\treturn {\n\t\t\t\ttype: 'MongoError',\n\t\t\t\toriginalError: error,\n\t\t\t\tdetails: {\n\t\t\t\t\tcode: (error as MongoServerError).code,\n\t\t\t\t\tcodeName: (error as MongoServerError).codeName,\n\t\t\t\t\tkeyPattern: (error as MongoServerError).keyPattern,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (error instanceof Error) {\n\t\t\treturn {\n\t\t\t\ttype: 'NodeError',\n\t\t\t\toriginalError: error,\n\t\t\t\tdetails: {\n\t\t\t\t\tname: error.name,\n\t\t\t\t\tcode: (error as NodeJS.ErrnoException).code,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\treturn { type: 'UnknownError', originalError: error };\n\t}\n}\n"]}
|
|
@@ -63,52 +63,36 @@ export declare class SchemaBuilder<T extends z.ZodRawShape> {
|
|
|
63
63
|
private baseSchema;
|
|
64
64
|
constructor(baseFields: T, includeTimestamps?: boolean, includeTracking?: boolean);
|
|
65
65
|
private createBaseSchema;
|
|
66
|
-
getBaseSchema(): z.ZodObject<T,
|
|
66
|
+
getBaseSchema(): z.ZodObject<T, "strict", z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any> extends infer T_1 ? { [k in keyof T_1]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any>[k]; } : never, z.baseObjectInputType<T> extends infer T_2 ? { [k_1 in keyof T_2]: z.baseObjectInputType<T>[k_1]; } : never>;
|
|
67
67
|
getEntitySchema(): z.ZodObject<z.objectUtil.extendShape<T, {
|
|
68
68
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
69
69
|
}> extends infer T_1 extends z.ZodRawShape ? { [k in keyof T_1]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
70
70
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
71
|
-
}>[k]>; } : never,
|
|
71
|
+
}>[k]>; } : never, "passthrough", z.ZodTypeAny, z.objectOutputType<z.objectUtil.extendShape<T, {
|
|
72
72
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
73
|
-
}> extends infer
|
|
73
|
+
}> extends infer T_2 extends z.ZodRawShape ? { [k in keyof T_2]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
74
74
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
75
|
-
}>[k]>; } : never
|
|
75
|
+
}>[k]>; } : never, z.ZodTypeAny, "passthrough">, z.objectInputType<z.objectUtil.extendShape<T, {
|
|
76
76
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
77
77
|
}> extends infer T_3 extends z.ZodRawShape ? { [k in keyof T_3]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
78
78
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
79
|
-
}>[k]>; } : never
|
|
80
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
81
|
-
}> extends infer T_7 extends z.ZodRawShape ? { [k in keyof T_7]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
82
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
83
|
-
}>[k]>; } : never> extends infer T_5 ? { [k_2 in keyof T_5]: z.baseObjectInputType<z.objectUtil.extendShape<T, {
|
|
84
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
85
|
-
}> extends infer T_6 extends z.ZodRawShape ? { [k in keyof T_6]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
86
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
87
|
-
}>[k]>; } : never>[k_2]; } : never>;
|
|
79
|
+
}>[k]>; } : never, z.ZodTypeAny, "passthrough">>;
|
|
88
80
|
getIdSchema(): z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
89
81
|
getUpdateSchema(excludeFields?: ExcludeFromUpdate): z.ZodObject<z.objectUtil.extendShape<T, {
|
|
90
82
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
91
83
|
}> extends infer T_1 extends z.ZodRawShape ? { [k in keyof T_1]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
92
84
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
93
|
-
}>[k]>; } : never,
|
|
85
|
+
}>[k]>; } : never, "passthrough", z.ZodTypeAny, z.objectOutputType<z.objectUtil.extendShape<T, {
|
|
94
86
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
95
|
-
}> extends infer
|
|
87
|
+
}> extends infer T_2 extends z.ZodRawShape ? { [k in keyof T_2]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
96
88
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
97
|
-
}>[k]>; } : never
|
|
89
|
+
}>[k]>; } : never, z.ZodTypeAny, "passthrough">, z.objectInputType<z.objectUtil.extendShape<T, {
|
|
98
90
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
99
91
|
}> extends infer T_3 extends z.ZodRawShape ? { [k in keyof T_3]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
100
92
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
101
|
-
}>[k]>; } : never
|
|
102
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
103
|
-
}> extends infer T_7 extends z.ZodRawShape ? { [k in keyof T_7]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
104
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
105
|
-
}>[k]>; } : never> extends infer T_5 ? { [k_2 in keyof T_5]: z.baseObjectInputType<z.objectUtil.extendShape<T, {
|
|
106
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
107
|
-
}> extends infer T_6 extends z.ZodRawShape ? { [k in keyof T_6]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
108
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
109
|
-
}>[k]>; } : never>[k_2]; } : never> | z.ZodObject<{
|
|
93
|
+
}>[k]>; } : never, z.ZodTypeAny, "passthrough">> | z.ZodObject<{
|
|
110
94
|
[x: string]: z.ZodOptional<z.ZodTypeAny>;
|
|
111
|
-
}, "
|
|
95
|
+
}, "strict", z.ZodTypeAny, {
|
|
112
96
|
[x: string]: any;
|
|
113
97
|
}, {
|
|
114
98
|
[x: string]: any;
|
|
@@ -129,52 +113,36 @@ export declare class SchemaBuilder<T extends z.ZodRawShape> {
|
|
|
129
113
|
[x: string]: any;
|
|
130
114
|
}>;
|
|
131
115
|
getAllSchemas(excludeFromUpdate?: ExcludeFromUpdate): {
|
|
132
|
-
BaseSchema: z.ZodObject<T,
|
|
116
|
+
BaseSchema: z.ZodObject<T, "strict", z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any> extends infer T_1 ? { [k in keyof T_1]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any>[k]; } : never, z.baseObjectInputType<T> extends infer T_2 ? { [k_1 in keyof T_2]: z.baseObjectInputType<T>[k_1]; } : never>;
|
|
133
117
|
EntitySchema: z.ZodObject<z.objectUtil.extendShape<T, {
|
|
134
118
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
135
119
|
}> extends infer T_3 extends z.ZodRawShape ? { [k_2 in keyof T_3]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
136
120
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
137
|
-
}>[k_2]>; } : never,
|
|
121
|
+
}>[k_2]>; } : never, "passthrough", z.ZodTypeAny, z.objectOutputType<z.objectUtil.extendShape<T, {
|
|
138
122
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
139
|
-
}> extends infer
|
|
123
|
+
}> extends infer T_4 extends z.ZodRawShape ? { [k_2 in keyof T_4]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
140
124
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
141
|
-
}>[k_2]>; } : never
|
|
125
|
+
}>[k_2]>; } : never, z.ZodTypeAny, "passthrough">, z.objectInputType<z.objectUtil.extendShape<T, {
|
|
142
126
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
143
127
|
}> extends infer T_5 extends z.ZodRawShape ? { [k_2 in keyof T_5]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
144
128
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
145
|
-
}>[k_2]>; } : never
|
|
146
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
147
|
-
}> extends infer T_9 extends z.ZodRawShape ? { [k_2 in keyof T_9]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
148
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
149
|
-
}>[k_2]>; } : never> extends infer T_7 ? { [k_4 in keyof T_7]: z.baseObjectInputType<z.objectUtil.extendShape<T, {
|
|
150
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
151
|
-
}> extends infer T_8 extends z.ZodRawShape ? { [k_2 in keyof T_8]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
152
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
153
|
-
}>[k_2]>; } : never>[k_4]; } : never>;
|
|
129
|
+
}>[k_2]>; } : never, z.ZodTypeAny, "passthrough">>;
|
|
154
130
|
IdSchema: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
155
131
|
UpdateSchema: z.ZodObject<z.objectUtil.extendShape<T, {
|
|
156
132
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
157
|
-
}> extends infer
|
|
158
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
159
|
-
}>[k_2]>; } : never, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
|
|
160
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
161
|
-
}> extends infer T_13 extends z.ZodRawShape ? { [k_2 in keyof T_13]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
162
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
163
|
-
}>[k_2]>; } : never>, any> extends infer T_11 ? { [k_3 in keyof T_11]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
|
|
164
|
-
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
165
|
-
}> extends infer T_12 extends z.ZodRawShape ? { [k_2 in keyof T_12]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
133
|
+
}> extends infer T_6 extends z.ZodRawShape ? { [k_2 in keyof T_6]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
166
134
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
167
|
-
}>[k_2]>; } : never
|
|
135
|
+
}>[k_2]>; } : never, "passthrough", z.ZodTypeAny, z.objectOutputType<z.objectUtil.extendShape<T, {
|
|
168
136
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
169
|
-
}> extends infer
|
|
137
|
+
}> extends infer T_7 extends z.ZodRawShape ? { [k_2 in keyof T_7]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
170
138
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
171
|
-
}>[k_2]>; } : never
|
|
139
|
+
}>[k_2]>; } : never, z.ZodTypeAny, "passthrough">, z.objectInputType<z.objectUtil.extendShape<T, {
|
|
172
140
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
173
|
-
}> extends infer
|
|
141
|
+
}> extends infer T_8 extends z.ZodRawShape ? { [k_2 in keyof T_8]: z.ZodOptional<z.objectUtil.extendShape<T, {
|
|
174
142
|
_id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
|
|
175
|
-
}>[k_2]>; } : never
|
|
143
|
+
}>[k_2]>; } : never, z.ZodTypeAny, "passthrough">> | z.ZodObject<{
|
|
176
144
|
[x: string]: z.ZodOptional<z.ZodTypeAny>;
|
|
177
|
-
}, "
|
|
145
|
+
}, "strict", z.ZodTypeAny, {
|
|
178
146
|
[x: string]: any;
|
|
179
147
|
}, {
|
|
180
148
|
[x: string]: any;
|
|
@@ -63,7 +63,7 @@ class ZodValidation {
|
|
|
63
63
|
schema = schema.min(options.minLength, options.minMessage || `${field} must be at least ${options.minLength} characters`);
|
|
64
64
|
}
|
|
65
65
|
if (options?.maxLength) {
|
|
66
|
-
schema = schema.max(options.maxLength, options.maxMessage || `${field}
|
|
66
|
+
schema = schema.max(options.maxLength, options.maxMessage || `${field} shouldn’t exceed ${options.maxLength} characters`);
|
|
67
67
|
}
|
|
68
68
|
if (options?.regex) {
|
|
69
69
|
schema = schema.regex(options.regex.pattern, options.regex.message);
|
|
@@ -178,17 +178,18 @@ class SchemaBuilder {
|
|
|
178
178
|
return zod_1.z.object({
|
|
179
179
|
...baseFields,
|
|
180
180
|
...additionalFields,
|
|
181
|
-
})
|
|
181
|
+
});
|
|
182
182
|
}
|
|
183
183
|
getBaseSchema() {
|
|
184
|
-
return this.baseSchema;
|
|
184
|
+
return this.baseSchema.strict();
|
|
185
185
|
}
|
|
186
186
|
getEntitySchema() {
|
|
187
187
|
return this.baseSchema
|
|
188
188
|
.extend({
|
|
189
189
|
_id: ZodValidation.objectId(),
|
|
190
190
|
})
|
|
191
|
-
.partial()
|
|
191
|
+
.partial()
|
|
192
|
+
.passthrough();
|
|
192
193
|
}
|
|
193
194
|
getIdSchema() {
|
|
194
195
|
return ZodValidation.objectId();
|
|
@@ -205,7 +206,7 @@ class SchemaBuilder {
|
|
|
205
206
|
filteredShape[key] = shape[key];
|
|
206
207
|
}
|
|
207
208
|
}
|
|
208
|
-
return zod_1.z.object(filteredShape).partial();
|
|
209
|
+
return zod_1.z.object(filteredShape).partial().strict();
|
|
209
210
|
}
|
|
210
211
|
getDeleteSchema() {
|
|
211
212
|
return zod_1.z.object({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"global-validation.js","sourceRoot":"/","sources":["utilities/validation/global-validation.ts"],"names":[],"mappings":";;;AAgsBA,kDAMC;AAtsBD,6BAAwB;AACxB,oDAAgD;AAehD,MAAa,aAAa;IAczB,MAAM,CAAC,QAAQ,CAAC,QAAgB,OAAO;QACtC,OAAO,OAAC,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IAAI,CAAC,UAAU,CAAC;QAE/C,IAAI,UAAU,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzC,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QACtF,CAAC;QAED,IAAI,YAAY,EAAE,CAAC;YAClB,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,aAAa,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,EAAE,GAAG,YAAY,EAAE,CAAC,CAAC;QACvF,CAAC;QAED,OAAO,MAAM,CAAC;IACf,CAAC;IAmBD,aAAa,CAAC,iBAAqC;QAClD,OAAO;YACN,UAAU,EAAE,IAAI,CAAC,aAAa,EAAE;YAChC,YAAY,EAAE,IAAI,CAAC,eAAe,EAAE;YACpC,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE;YAC5B,YAAY,EAAE,IAAI,CAAC,eAAe,CAAC,iBAAiB,CAAC;YACrD,YAAY,EAAE,IAAI,CAAC,eAAe,EAAE;SACpC,CAAC;IACH,CAAC;CACD;AAjND,sCAiNC;AA8CD,SAAgB,mBAAmB,CAClC,UAAa,EACb,oBAA6B,IAAI,EACjC,kBAA2B,KAAK;IAEhC,OAAO,IAAI,aAAa,CAAC,UAAU,EAAE,iBAAiB,EAAE,eAAe,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["import { z } from 'zod';\nimport { mongoose } from '@typegoose/typegoose';\n\n/**\n * Enhanced validation utilities for creating robust Zod schemas.\n * This class provides a collection of static methods to create common validation patterns.\n *\n * @example\n * ```typescript\n * const userSchema = z.object({\n * username: ZodValidation.requiredString(\"Username is required\"),\n * email: ZodValidation.email(),\n * role: ZodValidation.enumType(UserRole)\n * });\n * ```\n */\nexport class ZodValidation {\n\t/**\n\t * Creates a union type that accepts both string ObjectId and mongoose ObjectId instance.\n\t * This is useful when dealing with both raw string IDs and Mongoose ObjectId instances.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod union schema that accepts both string and ObjectId\n\t *\n\t * @example\n\t * ```typescript\n\t * const idSchema = ZodValidation.objectIdUnion();\n\t * // Accepts \"507f1f77bcf86cd799439011\" or new mongoose.Types.ObjectId(\"507f1f77bcf86cd799439011\")\n\t * ```\n\t */\n\tstatic objectId(field: string = 'Field') {\n\t\treturn z.union(\n\t\t\t[\n\t\t\t\tz\n\t\t\t\t\t.string({ required_error: `${field} is required` })\n\t\t\t\t\t.refine(val => mongoose.Types.ObjectId.isValid(val), {\n\t\t\t\t\t\tmessage: `${field} must be a valid ObjectID`,\n\t\t\t\t\t})\n\t\t\t\t\t.transform(val => new mongoose.Types.ObjectId(val)),\n\t\t\t\tz.instanceof(mongoose.Types.ObjectId, {\n\t\t\t\t\tmessage: `${field} must be a valid ObjectID`,\n\t\t\t\t}),\n\t\t\t],\n\t\t\t{ message: `${field} is required` }\n\t\t);\n\t}\n\n\t/**\n\t * Creates an enum validation with custom error message.\n\t * This validates that a value is one of the values defined in the enum.\n\t *\n\t * @template T - Type of the enum\n\t * @param enumObj - The enum object to validate against\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates against the provided enum\n\t *\n\t * @example\n\t * ```typescript\n\t * enum UserRole { ADMIN = \"admin\", USER = \"user\" }\n\t * const roleSchema = ZodValidation.enumType(UserRole, \"Invalid user role\");\n\t * ```\n\t */\n\tstatic enumType<T extends z.EnumLike>(enumObj: T, field: string = 'Field') {\n\t\treturn z.nativeEnum(enumObj, {\n\t\t\tmessage: `${field} must be one of: ${Object.values(enumObj).join(', ')}`,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a required number validation with a minimum length.\n\t * The number is also trimmed to remove leading/trailing whitespace.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @param min - Minimum number (optional)\n\t * @param max - MAximum number (optional)\n\t * @param options - options (optional)\n\t * @returns A Zod schema that validates numbers with minimum length\n\t *\n\t * @example\n\t * ```typescript\n\t * const nameSchema = ZodValidation.Number(\"Price\");\n\t * ```\n\t */\n\tstatic number(\n\t\tfield: string = 'Field',\n\t\toptions?: {\n\t\t\tmin?: number;\n\t\t\tmax?: number;\n\t\t\tisInt?: boolean;\n\t\t\tisPositive?: boolean;\n\t\t\tisNonpositive?: boolean;\n\t\t\tisNegative?: boolean;\n\t\t\tisNonnegative?: boolean;\n\t\t}\n\t) {\n\t\tlet schema = z.number({\n\t\t\trequired_error: `${field} is required`,\n\t\t\tinvalid_type_error: `${field} must be a number`,\n\t\t});\n\n\t\t// Range validation\n\t\tif (options?.min !== undefined) {\n\t\t\tschema = schema.gte(options?.min, {\n\t\t\t\tmessage: `${field} must be at least ${options?.min}`,\n\t\t\t});\n\t\t}\n\t\tif (options?.max !== undefined) {\n\t\t\tschema = schema.lte(options?.max, {\n\t\t\t\tmessage: `${field} must be at most ${options?.max}`,\n\t\t\t});\n\t\t}\n\n\t\t// Option validation\n\t\tif (options?.isInt) {\n\t\t\tschema = schema.int({ message: `${field} must be an integer` });\n\t\t}\n\t\tif (options?.isPositive) {\n\t\t\tschema = schema.positive({ message: `${field} must be positive` });\n\t\t}\n\t\tif (options?.isNonpositive) {\n\t\t\tschema = schema.nonpositive({ message: `${field} must be non-positive` });\n\t\t}\n\t\tif (options?.isNegative) {\n\t\t\tschema = schema.negative({ message: `${field} must be negative` });\n\t\t}\n\t\tif (options?.isNonnegative) {\n\t\t\tschema = schema.nonnegative({ message: `${field} must be non-negative` });\n\t\t}\n\n\t\treturn schema;\n\t}\n\n\t/**\n\t * Creates a required string validation with a minimum length.\n\t * The string is also trimmed to remove leading/trailing whitespace.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @param minLength - Minimum required length (optional)\n\t * @param maxLength - Maximum required length (optional)\n\t * @param regex - Regular expression (optional)\n\t * @returns A Zod schema that validates strings with minimum length\n\t *\n\t * @example\n\t * ```typescript\n\t * const nameSchema = ZodValidation.String(\"Name\");\n\t * ```\n\t */\n\tstatic string(\n\t\tfield: string = 'Field',\n\t\toptions?: {\n\t\t\tminLength?: number;\n\t\t\tmaxLength?: number;\n\t\t\toptional?: boolean;\n\t\t\tnullable?: boolean;\n\t\t\tminMessage?: string;\n\t\t\tmaxMessage?: string;\n\t\t\trequiredMessage?: string;\n\t\t\tregex?: { pattern: RegExp; message: string }; // Add regex option\n\t\t}\n\t) {\n\t\tlet schema = z.string({\n\t\t\trequired_error: options?.requiredMessage || `${field} is required`,\n\t\t});\n\n\t\tif (options?.minLength) {\n\t\t\tschema = schema.min(\n\t\t\t\toptions.minLength,\n\t\t\t\toptions.minMessage || `${field} must be at least ${options.minLength} characters`\n\t\t\t);\n\t\t}\n\n\t\tif (options?.maxLength) {\n\t\t\tschema = schema.max(\n\t\t\t\toptions.maxLength,\n\t\t\t\toptions.maxMessage || `${field} must be at most ${options.maxLength} characters`\n\t\t\t);\n\t\t}\n\n\t\t// Check for regex pattern and add regex validation\n\t\tif (options?.regex) {\n\t\t\tschema = schema.regex(options.regex.pattern, options.regex.message);\n\t\t}\n\n\t\tif (options?.nullable && options?.optional) {\n\t\t\treturn schema.nullish();\n\t\t}\n\t\tif (options?.nullable) {\n\t\t\treturn schema.nullable();\n\t\t}\n\t\tif (options?.optional) {\n\t\t\treturn schema.optional();\n\t\t}\n\n\t\treturn schema;\n\t}\n\n\t/**\n\t * Creates an email validation.\n\t * Validates that the string is a valid email address format.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates email addresses\n\t *\n\t * @example\n\t * ```typescript\n\t * const emailSchema = ZodValidation.email(\"Please enter a valid email\");\n\t * ```\n\t */\n\tstatic email(\n\t\tfield: string = 'Email',\n\t\toptions?: {\n\t\t\trequiredMessage?: string;\n\t\t\tinvalidMessage?: string;\n\t\t\toptional?: boolean;\n\t\t\tnullable?: boolean;\n\t\t}\n\t) {\n\t\tconst schema = z\n\t\t\t.string({\n\t\t\t\trequired_error: options?.requiredMessage || `${field} is required`,\n\t\t\t})\n\t\t\t.email(options?.invalidMessage || `${field} must be a valid email address`);\n\n\t\tif (options?.nullable && options?.optional) {\n\t\t\treturn schema.nullish();\n\t\t}\n\t\tif (options?.nullable) {\n\t\t\treturn schema.nullable();\n\t\t}\n\t\tif (options?.optional) {\n\t\t\treturn schema.optional();\n\t\t}\n\t\treturn schema;\n\t}\n\n\t/**\n\t * Creates a URL validation.\n\t * Validates that the string is a valid URL format.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates URLs\n\t *\n\t * @example\n\t * ```typescript\n\t * const websiteSchema = ZodValidation.url(\"Please enter a valid URL\");\n\t * ```\n\t */\n\tstatic url(field: string = 'Field') {\n\t\treturn z.string({ required_error: `${field} is required` }).url(`${field} must be a valid URL`);\n\t}\n\n\t/**\n\t * Creates a phone number validation schema using a regex pattern for global phone numbers.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates phone numbers\n\t *\n\t * @example\n\t * ```typescript\n\t * const phoneSchema = ZodValidation.phoneNumber(\"Phone number\");\n\t * ```\n\t */\n\tstatic phoneNumber(field: string = 'Field') {\n\t\treturn z\n\t\t\t.string({ required_error: `${field} is required` })\n\t\t\t.regex(/^[+]{1}(?:[0-9\\-\\\\(\\\\)\\\\/.]\\s?){6,15}[0-9]{1}$/, `${field} must be a valid phone number`);\n\t}\n\n\t/**\n\t * Creates a date validation.\n\t * Validates that the input is a JavaScript Date object.\n\t *@param field - The name of the field to be included in the error message\n\t *@param minDate - Minimum required date (optional)\n\t *@param maxDate - Maximum required date (optional)\n\t * @returns A Zod schema that validates Date objects\n\t *\n\t * @example\n\t * ```typescript\n\t * const createdAtSchema = ZodValidation.date();\n\t * ```\n\t */\n\tstatic date(field: string = 'Field', minDate?: Date, maxDate?: Date) {\n\t\treturn z\n\t\t\t.union(\n\t\t\t\t[\n\t\t\t\t\tz\n\t\t\t\t\t\t.string({ required_error: `${field} is required` })\n\t\t\t\t\t\t.refine(val => {\n\t\t\t\t\t\t\tconst date = new Date(val);\n\t\t\t\t\t\t\treturn !isNaN(date.getTime());\n\t\t\t\t\t\t}, `${field} must be a valid date`)\n\t\t\t\t\t\t.transform(val => new Date(val)),\n\t\t\t\t\tz.date({\n\t\t\t\t\t\trequired_error: `${field} is required`,\n\t\t\t\t\t\tinvalid_type_error: `${field} must be a valid date`,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t\t{ message: `${field} is required` }\n\t\t\t)\n\t\t\t.refine(\n\t\t\t\tval => minDate === undefined || val >= minDate,\n\t\t\t\t`${field} must be on or after ${minDate?.toISOString()}`\n\t\t\t)\n\t\t\t.refine(\n\t\t\t\tval => maxDate === undefined || val <= maxDate,\n\t\t\t\t`${field} must be on or before ${maxDate?.toISOString()}`\n\t\t\t);\n\t}\n\n\t/**\n\t * Creates a boolean validation with an optional default value.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates booleans\n\t *\n\t * @example\n\t * ```typescript\n\t * const isActiveSchema = ZodValidation.boolean(true); // Defaults to true\n\t * ```\n\t */\n\tstatic boolean(field: string = 'Field') {\n\t\treturn z.boolean({\n\t\t\trequired_error: `${field} is required`,\n\t\t\tinvalid_type_error: `${field} must be a boolean`,\n\t\t});\n\t}\n\n\t/**\n\t * Creates an array validation with optional minimum items constraint.\n\t *\n\t * @template T - Type of the schema for array items\n\t * @param schema - The schema for validating array items\n\t * @param field - The name of the field to be included in the error message\n\t * @param minItems - Minimum number of items required (optional)\n\t * @param maxItems - Maximum number of items required (optional)\n\t * @returns A Zod schema that validates arrays\n\t *\n\t * @example\n\t * ```typescript\n\t * const tagsSchema = ZodValidation.array(z.string(), \"At least one tag required\", 1);\n\t * ```\n\t */\n\tstatic array<T extends z.ZodTypeAny>(\n\t\tschema: T,\n\t\tfield: string = 'Array',\n\t\tminItems?: number,\n\t\tmaxItems?: number\n\t) {\n\t\tlet arraySchema = z.array(schema, {\n\t\t\trequired_error: `${field} is required`,\n\t\t});\n\n\t\tif (minItems === 1) {\n\t\t\tarraySchema = arraySchema.min(1, `${field} cannot be empty`);\n\t\t}\n\t\tif (minItems !== undefined && minItems !== 1) {\n\t\t\tarraySchema = arraySchema.min(minItems, `${field} must have at least ${minItems} items`);\n\t\t}\n\t\tif (maxItems !== undefined) {\n\t\t\tarraySchema = arraySchema.max(maxItems, `${field} must have at most ${maxItems} items`);\n\t\t}\n\n\t\treturn arraySchema;\n\t}\n\n\t/**\n\t * Standard timestamp fields for entities.\n\t * Includes createdAt, updatedAt, and deletedAt fields.\n\t *\n\t * @returns An object containing timestamp field schemas\n\t *\n\t * @example\n\t * ```typescript\n\t * const userSchema = z.object({\n\t * name: z.string(),\n\t * ...ZodValidation.timestamps()\n\t * });\n\t * ```\n\t */\n\tstatic timestamps() {\n\t\treturn {\n\t\t\tcreatedAt: z.date().nullable().optional(),\n\t\t\tupdatedAt: z.date().nullable().optional(),\n\t\t\tdeletedAt: z.date().nullable().optional(),\n\t\t};\n\t}\n\n\t/**\n\t * Common fields for tracking model metadata.\n\t * Includes timestamps and user tracking fields (createdBy, updatedBy, deletedBy).\n\t *\n\t * @returns An object containing tracking field schemas\n\t *\n\t * @example\n\t * ```typescript\n\t * const postSchema = z.object({\n\t * title: z.string(),\n\t * content: z.string(),\n\t * ...ZodValidation.trackingFields()\n\t * });\n\t * ```\n\t */\n\tstatic trackingFields() {\n\t\treturn {\n\t\t\tcreatedBy: ZodValidation.objectId().optional(),\n\t\t\tupdatedBy: ZodValidation.objectId().optional(),\n\t\t\tdeletedBy: ZodValidation.objectId().optional(),\n\t\t\t...ZodValidation.timestamps(),\n\t\t};\n\t}\n}\n\n/**\n * Represents the common fields to exclude from update operations.\n * This is used to specify which fields should not be updateable.\n *\n * @example\n * ```typescript\n * const excludeFields: ExcludeFromUpdate = {\n * createdAt: true,\n * createdBy: true,\n * status: true // Prevent status from being updated\n * };\n * ```\n */\nexport type ExcludeFromUpdate = {\n\tcreatedAt?: true;\n\tupdatedAt?: true;\n\tdeletedAt?: true;\n\tcreatedBy?: true;\n\t_id?: true;\n} & Record<string, true>;\n\n/**\n * Schema builder for creating consistent CRUD schemas.\n * Provides utility methods to generate schemas for create, read, update, and delete operations.\n *\n * @template T - Type of the base schema shape\n *\n * @example\n * ```typescript\n * const userBuilder = new SchemaBuilder({\n * name: z.string(),\n * email: z.string().email()\n * });\n *\n * const schemas = userBuilder.getAllSchemas();\n * ```\n */\nexport class SchemaBuilder<T extends z.ZodRawShape> {\n\tprivate baseSchema: z.ZodObject<T>;\n\n\t/**\n\t * Create a new schema builder\n\t *\n\t * @param baseFields - The base fields for the schema\n\t * @param includeTimestamps - Whether to include timestamp fields (default: true)\n\t * @param includeTracking - Whether to include tracking fields (createdBy, etc.) (default: false)\n\t *\n\t * @example\n\t * ```typescript\n\t * const userFields = {\n\t * name: ZodValidation.requiredString(),\n\t * email: ZodValidation.email()\n\t * };\n\t *\n\t * // With timestamps\n\t * const builder1 = new SchemaBuilder(userFields);\n\t *\n\t * // Without timestamps\n\t * const builder2 = new SchemaBuilder(userFields, false);\n\t *\n\t * // With tracking fields\n\t * const builder3 = new SchemaBuilder(userFields, true, true);\n\t * ```\n\t */\n\tconstructor(\n\t\tbaseFields: T,\n\t\tprivate includeTimestamps: boolean = true,\n\t\tprivate includeTracking: boolean = false\n\t) {\n\t\tthis.baseSchema = this.createBaseSchema(baseFields);\n\t}\n\n\t/**\n\t * Creates the base schema with optional timestamps and tracking fields.\n\t */\n\tprivate createBaseSchema(baseFields: T) {\n\t\tconst additionalFields = this.includeTracking\n\t\t\t? ZodValidation.trackingFields()\n\t\t\t: this.includeTimestamps\n\t\t\t\t? ZodValidation.timestamps()\n\t\t\t\t: {};\n\n\t\treturn z.object({\n\t\t\t...baseFields,\n\t\t\t...additionalFields,\n\t\t}).passthrough();\n\t}\n\n\t/**\n\t * Gets the base validation schema without ID.\n\t * Used for creating new entities.\n\t *\n\t * @returns The base schema for creating new entities\n\t *\n\t * @example\n\t * ```typescript\n\t * const createUserSchema = userBuilder.getBaseSchema();\n\t * ```\n\t */\n\tgetBaseSchema() {\n\t\treturn this.baseSchema;\n\t}\n\n\t/**\n\t * Gets the schema for entities with ID.\n\t * Used for representing complete entities with their ID.\n\t *\n\t * @returns The entity schema including ID\n\t *\n\t * @example\n\t * ```typescript\n\t * const userSchema = userBuilder.getEntitySchema();\n\t * ```\n\t */\n\tgetEntitySchema() {\n\t\treturn this.baseSchema\n\t\t\t.extend({\n\t\t\t\t_id: ZodValidation.objectId(),\n\t\t\t})\n\t\t\t.partial();\n\t}\n\n\t/**\n\t * Gets the schema for validating an entity ID.\n\t * Used for validating ID parameters in requests.\n\t *\n\t * @returns The ID validation schema\n\t *\n\t * @example\n\t * ```typescript\n\t * const userIdSchema = userBuilder.getIdSchema();\n\t * ```\n\t */\n\tgetIdSchema() {\n\t\treturn ZodValidation.objectId();\n\t}\n\n\t/**\n\t * Gets the schema for updating an entity, excluding specified fields.\n\t * Creates a partial schema where all fields are optional, and removes\n\t * fields that should not be updatable.\n\t *\n\t * @param excludeFields - Fields to exclude from update operations\n\t * @returns The update schema with excluded fields removed\n\t *\n\t * @example\n\t * ```typescript\n\t * // Prevent updating createdAt and status\n\t * const updateUserSchema = userBuilder.getUpdateSchema({\n\t * createdAt: true,\n\t * status: true\n\t * });\n\t * ```\n\t */\n\tgetUpdateSchema(excludeFields: ExcludeFromUpdate = { createdAt: true, updatedAt: true }) {\n\t\tconst entitySchema = this.getEntitySchema();\n\n\t\t// Simple approach - just make everything optional\n\t\tif (Object.keys(excludeFields).length === 0) {\n\t\t\treturn entitySchema;\n\t\t}\n\n\t\t// For the type-safe approach, we need to create a new schema\n\t\t// without the excluded fields and then make it partial\n\n\t\t// Get all fields from the entity schema\n\t\tconst shape = entitySchema._def.shape();\n\n\t\t// Filter out the fields we want to exclude\n\t\tconst filteredShape: z.ZodRawShape = {};\n\t\tfor (const key in shape) {\n\t\t\tif (!excludeFields[key as keyof typeof excludeFields]) {\n\t\t\t\tfilteredShape[key] = shape[key];\n\t\t\t}\n\t\t}\n\n\t\t// Create a new schema with the filtered fields\n\t\treturn z.object(filteredShape).partial();\n\t}\n\n\t/**\n\t * Gets the schema for validating a delete request.\n\t * Used for validating parameters in delete requests, including the entity ID and soft delete flag.\n\t *\n\t * @returns The delete validation schema\n\t *\n\t * @example\n\t * ```typescript\n\t * const deleteSchema = userBuilder.getDeleteSchema();\n\t * ```\n\t */\n\tgetDeleteSchema() {\n\t\treturn z.object({\n\t\t\t_id: ZodValidation.objectId('_id'),\n\t\t\tsoftDelete: ZodValidation.boolean('Soft Delete').default(true),\n\t\t});\n\t}\n\n\t/**\n\t * Creates an update schema by optionally extending the base schema with additional fields\n\t * and optionally omitting specified fields.\n\t *\n\t * @param extendFields - Optional fields to add to the schema (e.g., `_id`, `softDelete`).\n\t * @param omitFields - Optional fields to omit from the base schema (e.g., `name`).\n\t * @returns A new Zod schema for updates.\n\t */\n\tupdateBaseSchema(extendFields?: z.ZodRawShape, omitFields?: string[]) {\n\t\tlet schema: z.ZodObject<any> = this.baseSchema;\n\n\t\tif (omitFields && omitFields.length > 0) {\n\t\t\tschema = schema.omit(omitFields.reduce((acc, key) => ({ ...acc, [key]: true }), {}));\n\t\t}\n\n\t\tif (extendFields) {\n\t\t\tschema = schema.extend({ _id: ZodValidation.objectId().optional(), ...extendFields });\n\t\t}\n\n\t\treturn schema;\n\t}\n\n\t/**\n\t * Gets all common schemas for an entity.\n\t * Returns base, entity, ID, and update schemas in a single object.\n\t *\n\t * @param excludeFromUpdate - Fields to exclude from update operations\n\t * @returns Object containing all schemas\n\t *\n\t * @example\n\t * ```typescript\n\t * const {\n\t * BaseSchema, // For creating\n\t * EntitySchema, // For reading\n\t * IdSchema, // For validating IDs\n\t * UpdateSchema // For updating\n\t * } = userBuilder.getAllSchemas();\n\t * ```\n\t */\n\tgetAllSchemas(excludeFromUpdate?: ExcludeFromUpdate) {\n\t\treturn {\n\t\t\tBaseSchema: this.getBaseSchema(),\n\t\t\tEntitySchema: this.getEntitySchema(),\n\t\t\tIdSchema: this.getIdSchema(),\n\t\t\tUpdateSchema: this.getUpdateSchema(excludeFromUpdate),\n\t\t\tDeleteSchema: this.getDeleteSchema(),\n\t\t};\n\t}\n}\n\n/**\n * Type helper for creating DTO types from creation schemas.\n * Used to derive the type for creating new entities.\n *\n * @template T - The schema type\n *\n * @example\n * ```typescript\n * type CreateUserDTO = DTO<typeof UserValidationSchema>;\n * ```\n */\nexport type DTO<T extends z.ZodType> = z.infer<T>;\n\n/**\n * Creates a schema builder for an entity.\n * Helper function to create a new SchemaBuilder instance.\n *\n * @template T - Type of the base schema shape\n * @param baseFields - Base fields for the entity\n * @param includeTimestamps - Whether to include timestamp fields (default: true)\n * @param includeTracking - Whether to include tracking fields (default: false)\n * @returns A new SchemaBuilder instance\n *\n * @example\n * ```typescript\n * const userFields = {\n * name: ZodValidation.requiredString(),\n * email: ZodValidation.email()\n * };\n *\n * const userSchemaBuilder = createSchemaBuilder(userFields);\n * const userSchemaBuilder = createSchemaBuilder(userFields, true, true); // With tracking\n * ```\n */\nexport type PaginatedResponse<T> = {\n\tmetadata: {\n\t\tpage: number;\n\t\tsize: number;\n\t\ttotalElements: number;\n\t\ttotalPages: number;\n\t};\n\tdocuments: T[];\n};\n\nexport function createSchemaBuilder<T extends z.ZodRawShape>(\n\tbaseFields: T,\n\tincludeTimestamps: boolean = true,\n\tincludeTracking: boolean = false\n) {\n\treturn new SchemaBuilder(baseFields, includeTimestamps, includeTracking);\n}"]}
|
|
1
|
+
{"version":3,"file":"global-validation.js","sourceRoot":"/","sources":["utilities/validation/global-validation.ts"],"names":[],"mappings":";;;AAisBA,kDAMC;AAvsBD,6BAAwB;AACxB,oDAAgD;AAehD,MAAa,aAAa;IAczB,MAAM,CAAC,QAAQ,CAAC,QAAgB,OAAO;QACtC,OAAO,OAAC,CAAC,KAAK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ACnE,IAAI,MAAM,GAAqB,IAAI,CAAC,UAAU,CAAC;QAE/C,IAAI,UAAU,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzC,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QACtF,CAAC;QAED,IAAI,YAAY,EAAE,CAAC;YAClB,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,aAAa,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,EAAE,GAAG,YAAY,EAAE,CAAC,CAAC;QACvF,CAAC;QAED,OAAO,MAAM,CAAC;IACf,CAAC;IAmBD,aAAa,CAAC,iBAAqC;QAClD,OAAO;YACN,UAAU,EAAE,IAAI,CAAC,aAAa,EAAE;YAChC,YAAY,EAAE,IAAI,CAAC,eAAe,EAAE;YACpC,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE;YAC5B,YAAY,EAAE,IAAI,CAAC,eAAe,CAAC,iBAAiB,CAAC;YACrD,YAAY,EAAE,IAAI,CAAC,eAAe,EAAE;SACpC,CAAC;IACH,CAAC;CACD;AAlND,sCAkNC;AA8CD,SAAgB,mBAAmB,CAClC,UAAa,EACb,oBAA6B,IAAI,EACjC,kBAA2B,KAAK;IAEhC,OAAO,IAAI,aAAa,CAAC,UAAU,EAAE,iBAAiB,EAAE,eAAe,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["import { z } from 'zod';\nimport { mongoose } from '@typegoose/typegoose';\n\n/**\n * Enhanced validation utilities for creating robust Zod schemas.\n * This class provides a collection of static methods to create common validation patterns.\n *\n * @example\n * ```typescript\n * const userSchema = z.object({\n * username: ZodValidation.requiredString(\"Username is required\"),\n * email: ZodValidation.email(),\n * role: ZodValidation.enumType(UserRole)\n * });\n * ```\n */\nexport class ZodValidation {\n\t/**\n\t * Creates a union type that accepts both string ObjectId and mongoose ObjectId instance.\n\t * This is useful when dealing with both raw string IDs and Mongoose ObjectId instances.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod union schema that accepts both string and ObjectId\n\t *\n\t * @example\n\t * ```typescript\n\t * const idSchema = ZodValidation.objectIdUnion();\n\t * // Accepts \"507f1f77bcf86cd799439011\" or new mongoose.Types.ObjectId(\"507f1f77bcf86cd799439011\")\n\t * ```\n\t */\n\tstatic objectId(field: string = 'Field') {\n\t\treturn z.union(\n\t\t\t[\n\t\t\t\tz\n\t\t\t\t\t.string({ required_error: `${field} is required` })\n\t\t\t\t\t.refine(val => mongoose.Types.ObjectId.isValid(val), {\n\t\t\t\t\t\tmessage: `${field} must be a valid ObjectID`,\n\t\t\t\t\t})\n\t\t\t\t\t.transform(val => new mongoose.Types.ObjectId(val)),\n\t\t\t\tz.instanceof(mongoose.Types.ObjectId, {\n\t\t\t\t\tmessage: `${field} must be a valid ObjectID`,\n\t\t\t\t}),\n\t\t\t],\n\t\t\t{ message: `${field} is required` }\n\t\t);\n\t}\n\n\t/**\n\t * Creates an enum validation with custom error message.\n\t * This validates that a value is one of the values defined in the enum.\n\t *\n\t * @template T - Type of the enum\n\t * @param enumObj - The enum object to validate against\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates against the provided enum\n\t *\n\t * @example\n\t * ```typescript\n\t * enum UserRole { ADMIN = \"admin\", USER = \"user\" }\n\t * const roleSchema = ZodValidation.enumType(UserRole, \"Invalid user role\");\n\t * ```\n\t */\n\tstatic enumType<T extends z.EnumLike>(enumObj: T, field: string = 'Field') {\n\t\treturn z.nativeEnum(enumObj, {\n\t\t\tmessage: `${field} must be one of: ${Object.values(enumObj).join(', ')}`,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a required number validation with a minimum length.\n\t * The number is also trimmed to remove leading/trailing whitespace.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @param min - Minimum number (optional)\n\t * @param max - MAximum number (optional)\n\t * @param options - options (optional)\n\t * @returns A Zod schema that validates numbers with minimum length\n\t *\n\t * @example\n\t * ```typescript\n\t * const nameSchema = ZodValidation.Number(\"Price\");\n\t * ```\n\t */\n\tstatic number(\n\t\tfield: string = 'Field',\n\t\toptions?: {\n\t\t\tmin?: number;\n\t\t\tmax?: number;\n\t\t\tisInt?: boolean;\n\t\t\tisPositive?: boolean;\n\t\t\tisNonpositive?: boolean;\n\t\t\tisNegative?: boolean;\n\t\t\tisNonnegative?: boolean;\n\t\t}\n\t) {\n\t\tlet schema = z.number({\n\t\t\trequired_error: `${field} is required`,\n\t\t\tinvalid_type_error: `${field} must be a number`,\n\t\t});\n\n\t\t// Range validation\n\t\tif (options?.min !== undefined) {\n\t\t\tschema = schema.gte(options?.min, {\n\t\t\t\tmessage: `${field} must be at least ${options?.min}`,\n\t\t\t});\n\t\t}\n\t\tif (options?.max !== undefined) {\n\t\t\tschema = schema.lte(options?.max, {\n\t\t\t\tmessage: `${field} must be at most ${options?.max}`,\n\t\t\t});\n\t\t}\n\n\t\t// Option validation\n\t\tif (options?.isInt) {\n\t\t\tschema = schema.int({ message: `${field} must be an integer` });\n\t\t}\n\t\tif (options?.isPositive) {\n\t\t\tschema = schema.positive({ message: `${field} must be positive` });\n\t\t}\n\t\tif (options?.isNonpositive) {\n\t\t\tschema = schema.nonpositive({ message: `${field} must be non-positive` });\n\t\t}\n\t\tif (options?.isNegative) {\n\t\t\tschema = schema.negative({ message: `${field} must be negative` });\n\t\t}\n\t\tif (options?.isNonnegative) {\n\t\t\tschema = schema.nonnegative({ message: `${field} must be non-negative` });\n\t\t}\n\n\t\treturn schema;\n\t}\n\n\t/**\n\t * Creates a required string validation with a minimum length.\n\t * The string is also trimmed to remove leading/trailing whitespace.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @param minLength - Minimum required length (optional)\n\t * @param maxLength - Maximum required length (optional)\n\t * @param regex - Regular expression (optional)\n\t * @returns A Zod schema that validates strings with minimum length\n\t *\n\t * @example\n\t * ```typescript\n\t * const nameSchema = ZodValidation.String(\"Name\");\n\t * ```\n\t */\n\tstatic string(\n\t\tfield: string = 'Field',\n\t\toptions?: {\n\t\t\tminLength?: number;\n\t\t\tmaxLength?: number;\n\t\t\toptional?: boolean;\n\t\t\tnullable?: boolean;\n\t\t\tminMessage?: string;\n\t\t\tmaxMessage?: string;\n\t\t\trequiredMessage?: string;\n\t\t\tregex?: { pattern: RegExp; message: string }; // Add regex option\n\t\t}\n\t) {\n\t\tlet schema = z.string({\n\t\t\trequired_error: options?.requiredMessage || `${field} is required`,\n\t\t});\n\n\t\tif (options?.minLength) {\n\t\t\tschema = schema.min(\n\t\t\t\toptions.minLength,\n\t\t\t\toptions.minMessage || `${field} must be at least ${options.minLength} characters`\n\t\t\t);\n\t\t}\n\n\t\tif (options?.maxLength) {\n\t\t\tschema = schema.max(\n\t\t\t\toptions.maxLength,\n\t\t\t\toptions.maxMessage || `${field} shouldn’t exceed ${options.maxLength} characters`\n\t\t\t);\n\t\t}\n\n\t\t// Check for regex pattern and add regex validation\n\t\tif (options?.regex) {\n\t\t\tschema = schema.regex(options.regex.pattern, options.regex.message);\n\t\t}\n\n\t\tif (options?.nullable && options?.optional) {\n\t\t\treturn schema.nullish();\n\t\t}\n\t\tif (options?.nullable) {\n\t\t\treturn schema.nullable();\n\t\t}\n\t\tif (options?.optional) {\n\t\t\treturn schema.optional();\n\t\t}\n\n\t\treturn schema;\n\t}\n\n\t/**\n\t * Creates an email validation.\n\t * Validates that the string is a valid email address format.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates email addresses\n\t *\n\t * @example\n\t * ```typescript\n\t * const emailSchema = ZodValidation.email(\"Please enter a valid email\");\n\t * ```\n\t */\n\tstatic email(\n\t\tfield: string = 'Email',\n\t\toptions?: {\n\t\t\trequiredMessage?: string;\n\t\t\tinvalidMessage?: string;\n\t\t\toptional?: boolean;\n\t\t\tnullable?: boolean;\n\t\t}\n\t) {\n\t\tconst schema = z\n\t\t\t.string({\n\t\t\t\trequired_error: options?.requiredMessage || `${field} is required`,\n\t\t\t})\n\t\t\t.email(options?.invalidMessage || `${field} must be a valid email address`);\n\n\t\tif (options?.nullable && options?.optional) {\n\t\t\treturn schema.nullish();\n\t\t}\n\t\tif (options?.nullable) {\n\t\t\treturn schema.nullable();\n\t\t}\n\t\tif (options?.optional) {\n\t\t\treturn schema.optional();\n\t\t}\n\t\treturn schema;\n\t}\n\n\t/**\n\t * Creates a URL validation.\n\t * Validates that the string is a valid URL format.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates URLs\n\t *\n\t * @example\n\t * ```typescript\n\t * const websiteSchema = ZodValidation.url(\"Please enter a valid URL\");\n\t * ```\n\t */\n\tstatic url(field: string = 'Field') {\n\t\treturn z.string({ required_error: `${field} is required` }).url(`${field} must be a valid URL`);\n\t}\n\n\t/**\n\t * Creates a phone number validation schema using a regex pattern for global phone numbers.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates phone numbers\n\t *\n\t * @example\n\t * ```typescript\n\t * const phoneSchema = ZodValidation.phoneNumber(\"Phone number\");\n\t * ```\n\t */\n\tstatic phoneNumber(field: string = 'Field') {\n\t\treturn z\n\t\t\t.string({ required_error: `${field} is required` })\n\t\t\t.regex(/^[+]{1}(?:[0-9\\-\\\\(\\\\)\\\\/.]\\s?){6,15}[0-9]{1}$/, `${field} must be a valid phone number`);\n\t}\n\n\t/**\n\t * Creates a date validation.\n\t * Validates that the input is a JavaScript Date object.\n\t *@param field - The name of the field to be included in the error message\n\t *@param minDate - Minimum required date (optional)\n\t *@param maxDate - Maximum required date (optional)\n\t * @returns A Zod schema that validates Date objects\n\t *\n\t * @example\n\t * ```typescript\n\t * const createdAtSchema = ZodValidation.date();\n\t * ```\n\t */\n\tstatic date(field: string = 'Field', minDate?: Date, maxDate?: Date) {\n\t\treturn z\n\t\t\t.union(\n\t\t\t\t[\n\t\t\t\t\tz\n\t\t\t\t\t\t.string({ required_error: `${field} is required` })\n\t\t\t\t\t\t.refine(val => {\n\t\t\t\t\t\t\tconst date = new Date(val);\n\t\t\t\t\t\t\treturn !isNaN(date.getTime());\n\t\t\t\t\t\t}, `${field} must be a valid date`)\n\t\t\t\t\t\t.transform(val => new Date(val)),\n\t\t\t\t\tz.date({\n\t\t\t\t\t\trequired_error: `${field} is required`,\n\t\t\t\t\t\tinvalid_type_error: `${field} must be a valid date`,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t\t{ message: `${field} is required` }\n\t\t\t)\n\t\t\t.refine(\n\t\t\t\tval => minDate === undefined || val >= minDate,\n\t\t\t\t`${field} must be on or after ${minDate?.toISOString()}`\n\t\t\t)\n\t\t\t.refine(\n\t\t\t\tval => maxDate === undefined || val <= maxDate,\n\t\t\t\t`${field} must be on or before ${maxDate?.toISOString()}`\n\t\t\t);\n\t}\n\n\t/**\n\t * Creates a boolean validation with an optional default value.\n\t *\n\t * @param field - The name of the field to be included in the error message\n\t * @returns A Zod schema that validates booleans\n\t *\n\t * @example\n\t * ```typescript\n\t * const isActiveSchema = ZodValidation.boolean(true); // Defaults to true\n\t * ```\n\t */\n\tstatic boolean(field: string = 'Field') {\n\t\treturn z.boolean({\n\t\t\trequired_error: `${field} is required`,\n\t\t\tinvalid_type_error: `${field} must be a boolean`,\n\t\t});\n\t}\n\n\t/**\n\t * Creates an array validation with optional minimum items constraint.\n\t *\n\t * @template T - Type of the schema for array items\n\t * @param schema - The schema for validating array items\n\t * @param field - The name of the field to be included in the error message\n\t * @param minItems - Minimum number of items required (optional)\n\t * @param maxItems - Maximum number of items required (optional)\n\t * @returns A Zod schema that validates arrays\n\t *\n\t * @example\n\t * ```typescript\n\t * const tagsSchema = ZodValidation.array(z.string(), \"At least one tag required\", 1);\n\t * ```\n\t */\n\tstatic array<T extends z.ZodTypeAny>(\n\t\tschema: T,\n\t\tfield: string = 'Array',\n\t\tminItems?: number,\n\t\tmaxItems?: number\n\t) {\n\t\tlet arraySchema = z.array(schema, {\n\t\t\trequired_error: `${field} is required`,\n\t\t});\n\n\t\tif (minItems === 1) {\n\t\t\tarraySchema = arraySchema.min(1, `${field} cannot be empty`);\n\t\t}\n\t\tif (minItems !== undefined && minItems !== 1) {\n\t\t\tarraySchema = arraySchema.min(minItems, `${field} must have at least ${minItems} items`);\n\t\t}\n\t\tif (maxItems !== undefined) {\n\t\t\tarraySchema = arraySchema.max(maxItems, `${field} must have at most ${maxItems} items`);\n\t\t}\n\n\t\treturn arraySchema;\n\t}\n\n\t/**\n\t * Standard timestamp fields for entities.\n\t * Includes createdAt, updatedAt, and deletedAt fields.\n\t *\n\t * @returns An object containing timestamp field schemas\n\t *\n\t * @example\n\t * ```typescript\n\t * const userSchema = z.object({\n\t * name: z.string(),\n\t * ...ZodValidation.timestamps()\n\t * });\n\t * ```\n\t */\n\tstatic timestamps() {\n\t\treturn {\n\t\t\tcreatedAt: z.date().nullable().optional(),\n\t\t\tupdatedAt: z.date().nullable().optional(),\n\t\t\tdeletedAt: z.date().nullable().optional(),\n\t\t};\n\t}\n\n\t/**\n\t * Common fields for tracking model metadata.\n\t * Includes timestamps and user tracking fields (createdBy, updatedBy, deletedBy).\n\t *\n\t * @returns An object containing tracking field schemas\n\t *\n\t * @example\n\t * ```typescript\n\t * const postSchema = z.object({\n\t * title: z.string(),\n\t * content: z.string(),\n\t * ...ZodValidation.trackingFields()\n\t * });\n\t * ```\n\t */\n\tstatic trackingFields() {\n\t\treturn {\n\t\t\tcreatedBy: ZodValidation.objectId().optional(),\n\t\t\tupdatedBy: ZodValidation.objectId().optional(),\n\t\t\tdeletedBy: ZodValidation.objectId().optional(),\n\t\t\t...ZodValidation.timestamps(),\n\t\t};\n\t}\n}\n\n/**\n * Represents the common fields to exclude from update operations.\n * This is used to specify which fields should not be updateable.\n *\n * @example\n * ```typescript\n * const excludeFields: ExcludeFromUpdate = {\n * createdAt: true,\n * createdBy: true,\n * status: true // Prevent status from being updated\n * };\n * ```\n */\nexport type ExcludeFromUpdate = {\n\tcreatedAt?: true;\n\tupdatedAt?: true;\n\tdeletedAt?: true;\n\tcreatedBy?: true;\n\t_id?: true;\n} & Record<string, true>;\n\n/**\n * Schema builder for creating consistent CRUD schemas.\n * Provides utility methods to generate schemas for create, read, update, and delete operations.\n *\n * @template T - Type of the base schema shape\n *\n * @example\n * ```typescript\n * const userBuilder = new SchemaBuilder({\n * name: z.string(),\n * email: z.string().email()\n * });\n *\n * const schemas = userBuilder.getAllSchemas();\n * ```\n */\nexport class SchemaBuilder<T extends z.ZodRawShape> {\n\tprivate baseSchema: z.ZodObject<T>;\n\n\t/**\n\t * Create a new schema builder\n\t *\n\t * @param baseFields - The base fields for the schema\n\t * @param includeTimestamps - Whether to include timestamp fields (default: true)\n\t * @param includeTracking - Whether to include tracking fields (createdBy, etc.) (default: false)\n\t *\n\t * @example\n\t * ```typescript\n\t * const userFields = {\n\t * name: ZodValidation.requiredString(),\n\t * email: ZodValidation.email()\n\t * };\n\t *\n\t * // With timestamps\n\t * const builder1 = new SchemaBuilder(userFields);\n\t *\n\t * // Without timestamps\n\t * const builder2 = new SchemaBuilder(userFields, false);\n\t *\n\t * // With tracking fields\n\t * const builder3 = new SchemaBuilder(userFields, true, true);\n\t * ```\n\t */\n\tconstructor(\n\t\tbaseFields: T,\n\t\tprivate includeTimestamps: boolean = true,\n\t\tprivate includeTracking: boolean = false\n\t) {\n\t\tthis.baseSchema = this.createBaseSchema(baseFields);\n\t}\n\n\t/**\n\t * Creates the base schema with optional timestamps and tracking fields.\n\t */\n\tprivate createBaseSchema(baseFields: T) {\n\t\tconst additionalFields = this.includeTracking\n\t\t\t? ZodValidation.trackingFields()\n\t\t\t: this.includeTimestamps\n\t\t\t\t? ZodValidation.timestamps()\n\t\t\t\t: {};\n\n\t\treturn z.object({\n\t\t\t...baseFields,\n\t\t\t...additionalFields,\n\t\t});\n\t}\n\n\t/**\n\t * Gets the base validation schema without ID.\n\t * Used for creating new entities.\n\t *\n\t * @returns The base schema for creating new entities\n\t *\n\t * @example\n\t * ```typescript\n\t * const createUserSchema = userBuilder.getBaseSchema();\n\t * ```\n\t */\n\tgetBaseSchema() {\n\t\treturn this.baseSchema.strict();\n\t}\n\n\t/**\n\t * Gets the schema for entities with ID.\n\t * Used for representing complete entities with their ID.\n\t *\n\t * @returns The entity schema including ID\n\t *\n\t * @example\n\t * ```typescript\n\t * const userSchema = userBuilder.getEntitySchema();\n\t * ```\n\t */\n\tgetEntitySchema() {\n\t\treturn this.baseSchema\n\t\t\t.extend({\n\t\t\t\t_id: ZodValidation.objectId(),\n\t\t\t})\n\t\t\t.partial()\n\t\t\t.passthrough();\n\t}\n\n\t/**\n\t * Gets the schema for validating an entity ID.\n\t * Used for validating ID parameters in requests.\n\t *\n\t * @returns The ID validation schema\n\t *\n\t * @example\n\t * ```typescript\n\t * const userIdSchema = userBuilder.getIdSchema();\n\t * ```\n\t */\n\tgetIdSchema() {\n\t\treturn ZodValidation.objectId();\n\t}\n\n\t/**\n\t * Gets the schema for updating an entity, excluding specified fields.\n\t * Creates a partial schema where all fields are optional, and removes\n\t * fields that should not be updatable.\n\t *\n\t * @param excludeFields - Fields to exclude from update operations\n\t * @returns The update schema with excluded fields removed\n\t *\n\t * @example\n\t * ```typescript\n\t * // Prevent updating createdAt and status\n\t * const updateUserSchema = userBuilder.getUpdateSchema({\n\t * createdAt: true,\n\t * status: true\n\t * });\n\t * ```\n\t */\n\tgetUpdateSchema(excludeFields: ExcludeFromUpdate = { createdAt: true, updatedAt: true }) {\n\t\tconst entitySchema = this.getEntitySchema();\n\n\t\t// Simple approach - just make everything optional\n\t\tif (Object.keys(excludeFields).length === 0) {\n\t\t\treturn entitySchema;\n\t\t}\n\n\t\t// For the type-safe approach, we need to create a new schema\n\t\t// without the excluded fields and then make it partial\n\n\t\t// Get all fields from the entity schema\n\t\tconst shape = entitySchema._def.shape();\n\n\t\t// Filter out the fields we want to exclude\n\t\tconst filteredShape: z.ZodRawShape = {};\n\t\tfor (const key in shape) {\n\t\t\tif (!excludeFields[key as keyof typeof excludeFields]) {\n\t\t\t\tfilteredShape[key] = shape[key];\n\t\t\t}\n\t\t}\n\n\t\t// Create a new schema with the filtered fields\n\t\treturn z.object(filteredShape).partial().strict();\n\t}\n\n\t/**\n\t * Gets the schema for validating a delete request.\n\t * Used for validating parameters in delete requests, including the entity ID and soft delete flag.\n\t *\n\t * @returns The delete validation schema\n\t *\n\t * @example\n\t * ```typescript\n\t * const deleteSchema = userBuilder.getDeleteSchema();\n\t * ```\n\t */\n\tgetDeleteSchema() {\n\t\treturn z.object({\n\t\t\t_id: ZodValidation.objectId('_id'),\n\t\t\tsoftDelete: ZodValidation.boolean('Soft Delete').default(true),\n\t\t});\n\t}\n\n\t/**\n\t * Creates an update schema by optionally extending the base schema with additional fields\n\t * and optionally omitting specified fields.\n\t *\n\t * @param extendFields - Optional fields to add to the schema (e.g., `_id`, `softDelete`).\n\t * @param omitFields - Optional fields to omit from the base schema (e.g., `name`).\n\t * @returns A new Zod schema for updates.\n\t */\n\tupdateBaseSchema(extendFields?: z.ZodRawShape, omitFields?: string[]) {\n\t\tlet schema: z.ZodObject<any> = this.baseSchema;\n\n\t\tif (omitFields && omitFields.length > 0) {\n\t\t\tschema = schema.omit(omitFields.reduce((acc, key) => ({ ...acc, [key]: true }), {}));\n\t\t}\n\n\t\tif (extendFields) {\n\t\t\tschema = schema.extend({ _id: ZodValidation.objectId().optional(), ...extendFields });\n\t\t}\n\n\t\treturn schema;\n\t}\n\n\t/**\n\t * Gets all common schemas for an entity.\n\t * Returns base, entity, ID, and update schemas in a single object.\n\t *\n\t * @param excludeFromUpdate - Fields to exclude from update operations\n\t * @returns Object containing all schemas\n\t *\n\t * @example\n\t * ```typescript\n\t * const {\n\t * BaseSchema, // For creating\n\t * EntitySchema, // For reading\n\t * IdSchema, // For validating IDs\n\t * UpdateSchema // For updating\n\t * } = userBuilder.getAllSchemas();\n\t * ```\n\t */\n\tgetAllSchemas(excludeFromUpdate?: ExcludeFromUpdate) {\n\t\treturn {\n\t\t\tBaseSchema: this.getBaseSchema(),\n\t\t\tEntitySchema: this.getEntitySchema(),\n\t\t\tIdSchema: this.getIdSchema(),\n\t\t\tUpdateSchema: this.getUpdateSchema(excludeFromUpdate),\n\t\t\tDeleteSchema: this.getDeleteSchema(),\n\t\t};\n\t}\n}\n\n/**\n * Type helper for creating DTO types from creation schemas.\n * Used to derive the type for creating new entities.\n *\n * @template T - The schema type\n *\n * @example\n * ```typescript\n * type CreateUserDTO = DTO<typeof UserValidationSchema>;\n * ```\n */\nexport type DTO<T extends z.ZodType> = z.infer<T>;\n\n/**\n * Creates a schema builder for an entity.\n * Helper function to create a new SchemaBuilder instance.\n *\n * @template T - Type of the base schema shape\n * @param baseFields - Base fields for the entity\n * @param includeTimestamps - Whether to include timestamp fields (default: true)\n * @param includeTracking - Whether to include tracking fields (default: false)\n * @returns A new SchemaBuilder instance\n *\n * @example\n * ```typescript\n * const userFields = {\n * name: ZodValidation.requiredString(),\n * email: ZodValidation.email()\n * };\n *\n * const userSchemaBuilder = createSchemaBuilder(userFields);\n * const userSchemaBuilder = createSchemaBuilder(userFields, true, true); // With tracking\n * ```\n */\nexport type PaginatedResponse<T> = {\n\tmetadata: {\n\t\tpage: number;\n\t\tsize: number;\n\t\ttotalElements: number;\n\t\ttotalPages: number;\n\t};\n\tdocuments: T[];\n};\n\nexport function createSchemaBuilder<T extends z.ZodRawShape>(\n\tbaseFields: T,\n\tincludeTimestamps: boolean = true,\n\tincludeTracking: boolean = false\n) {\n\treturn new SchemaBuilder(baseFields, includeTimestamps, includeTracking);\n}\n"]}
|