arkos 1.4.0-canary.12 → 1.4.0-canary.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/modules/error-handler/error-handler.controller.js +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/app-error.js +4 -3
- package/dist/cjs/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js +7 -5
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js +1 -0
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/cjs/utils/cli/generate.js +0 -1
- package/dist/cjs/utils/cli/generate.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +3 -3
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +3 -2
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/app-error.js +4 -3
- package/dist/esm/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js +7 -5
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/index.js +1 -0
- package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/esm/utils/cli/generate.js +0 -1
- package/dist/esm/utils/cli/generate.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +3 -3
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +3 -2
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +1 -1
- package/package.json +1 -1
|
@@ -121,7 +121,7 @@ function sendProductionError(err, req, res) {
|
|
|
121
121
|
}
|
|
122
122
|
res.status(err.statusCode).json({
|
|
123
123
|
title: "Internal server error",
|
|
124
|
-
message: "
|
|
124
|
+
message: "Internal server error, please try again later.",
|
|
125
125
|
});
|
|
126
126
|
}
|
|
127
127
|
process.on("SIGTERM", () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BA6DC;AA/ED,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAG,EAAE,GAAG,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,CAAC;IAE7C,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EA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AAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error = { ...err, message: err.message };\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(err, req, res);\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BA6DC;AA/ED,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAA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CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;SACrB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error = { ...err, message: err.message };\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(err, req, res);\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
@@ -4,13 +4,12 @@ class AppError extends Error {
|
|
|
4
4
|
constructor(message, statusCode, code, meta) {
|
|
5
5
|
super(message);
|
|
6
6
|
this.code = "Unknown";
|
|
7
|
-
this.meta = {};
|
|
8
7
|
this.message = message || "An error occurred, try again!";
|
|
9
8
|
this.statusCode = statusCode;
|
|
10
9
|
this.status = `${statusCode}`.startsWith("4") ? "fail" : "error";
|
|
11
10
|
this.isOperational = true;
|
|
12
|
-
if (typeof code === typeof meta)
|
|
13
|
-
throw
|
|
11
|
+
if (code && meta && typeof code === typeof meta)
|
|
12
|
+
throw new AppError(`meta and code must not both be ${typeof code}, one must be of type object and other string. but received ${JSON.stringify({ meta, code })}`, 500, "AppErrorMisuse", { meta, code });
|
|
14
13
|
if (typeof code === "string")
|
|
15
14
|
this.code = code || "Unknown";
|
|
16
15
|
if (typeof code === "object")
|
|
@@ -19,6 +18,8 @@ class AppError extends Error {
|
|
|
19
18
|
this.code = meta || "Unknown";
|
|
20
19
|
if (typeof meta === "object")
|
|
21
20
|
this.meta = meta;
|
|
21
|
+
if (!code)
|
|
22
|
+
this.code = "Unknown";
|
|
22
23
|
this.missing = false;
|
|
23
24
|
Error.captureStackTrace(this, this.constructor);
|
|
24
25
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-error.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/app-error.ts"],"names":[],"mappings":";;AAgCA,MAAM,QAAS,SAAQ,KAAK;IAgB1B,YACE,OAAe,EACf,UAAkB,EAClB,IAAmC,EACnC,IAAmC;QAEnC,KAAK,CAAC,OAAO,CAAC,CAAC;QAjBjB,SAAI,GAAY,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"app-error.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/app-error.ts"],"names":[],"mappings":";;AAgCA,MAAM,QAAS,SAAQ,KAAK;IAgB1B,YACE,OAAe,EACf,UAAkB,EAClB,IAAmC,EACnC,IAAmC;QAEnC,KA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* @property {number} statusCode - HTTP status code of the error.\n * @property {string} status - Status message derived from the status code (`fail` for 4xx, `error` for 5xx).\n * @property {boolean} [missing=false] - Flag to indicate if a resource is missing.\n * @property {boolean} isOperational - Indicates if the error is operational (intended for client visibility).\n * @property {string} [code] - Optional error code for categorization.\n * @property {Record<string, any>} [meta] - Additional metadata related to the error.\n *\n * @example\n * ```typescript\n *\n * function getUser(id: string) {\n * if (!id) {\n * throw new AppError('User ID is required', 400, 'UserIDMissing', { field: 'id' });\n * }\n * // Simulate a user not found scenario\n * throw new AppError('User not found', 404, 'UserNotFound', { userId: id });\n * }\n *\n * try {\n * getUser('');\n * } catch (error) {\n * if (error instanceof AppError) {\n * console.error(`Error: ${error.message}, Code: ${error.code}, Status: ${error.status}`);\n * }\n * }\n * ```\n */\nclass AppError extends Error {\n statusCode: number;\n status: string;\n public missing?: boolean;\n public isOperational: boolean;\n code?: string = \"Unknown\";\n meta?: Record<string, any>;\n\n /**\n * Creates an instance of AppError.\n *\n * @param {string} message - The error message.\n * @param {number} statusCode - The HTTP status code.\n * @param {Record<string, any>} [meta] - Additional metadata for debugging or client feedback.\n * @param {string} [code] - A custom error code for categorization.\n */\n constructor(\n message: string,\n statusCode: number,\n code?: string | Record<string, any>,\n meta?: Record<string, any> | string\n ) {\n super(message);\n\n this.message = message || \"An error occurred, try again!\";\n this.statusCode = statusCode;\n this.status = `${statusCode}`.startsWith(\"4\") ? \"fail\" : \"error\";\n this.isOperational = true;\n\n if (code && meta && typeof code === typeof meta)\n throw new AppError(\n `meta and code must not both be ${typeof code}, one must be of type object and other string. but received ${JSON.stringify({ meta, code })}`,\n 500,\n \"AppErrorMisuse\",\n { meta, code }\n );\n\n if (typeof code === \"string\") this.code = code || \"Unknown\";\n if (typeof code === \"object\") this.meta = code;\n if (typeof meta === \"string\") this.code = meta || \"Unknown\";\n if (typeof meta === \"object\") this.meta = meta;\n if (!code) this.code = \"Unknown\";\n\n this.missing = false;\n\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\nexport default AppError;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AASA,wCAEC;AAED,4CAEC;AAED,8EAIC;AAED,8DAIC;AAED,sEAIC;AAED,oEAIC;AAED,kEAGC;AAED,wEAIC;AAED,sEAGC;AAED,8DAIC;AAED,kEAIC;AAED,0EAIC;AAED,kEAIC;AAED,oEAIC;AAED,0EAIC;AAED,8DAIC;AAED,0DAIC;AAED,sEAIC;AAED,oEAIC;AAED,gFAIC;AAED,0EAIC;AAED,gFAIC;AAED,4EAIC;AAED,gEAGC;AAED,oEAIC;AAED,wDAGC;AAED,0DAGC;AAED,sDAGC;AAED,0DAGC;AAED,gEAIC;AAED,8CAIC;AAED,gDAGC;AAED,kEAGC;AAED,kDAKC;AAED,wDAGC;AAED,0DAQC;AAED,sFAOC;AA/ND,4DAAmC;AASnC,SAAgB,cAAc;IAC5B,OAAO,IAAI,mBAAQ,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC;AAED,SAAgB,gBAAgB;IAC9B,OAAO,IAAI,mBAAQ,CAAC,2CAA2C,EAAE,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAgB,iCAAiC,CAAC,GAAa;IAC7D,MAAM,OAAO,GACX,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACjE,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,yBAAyB,CAAC,CAAW;IACnD,MAAM,OAAO,GACX,mFAAmF,CAAC;IACtF,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,S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,iCAAiC,EACjC,GAAG,EACH,EAAE,EACF,sBAAsB,CACvB,CAAC;AACJ,CAAC","sourcesContent":["import AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string; // Prisma-specific error code\n message: string; // Error message\n meta?: Record<string, any>; // Metadata provided by Prisma\n name?: string; // Error name\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message =\n err?.message?.split(\"\\n\")[err?.message.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(_: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(_: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(_: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(_: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(message, 409);\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(_: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(_: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(_: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(_: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(_: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(_: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(_: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(_: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(_: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(_: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(_: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as the required record was not found`;\n return new AppError(message, 404, err.meta || {}, \"RecordNotFound\");\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n {},\n \"DatabaseNotAvailable\"\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AASA,wCAEC;AAED,4CAEC;AAED,8EAIC;AAED,8DAIC;AAED,sEAIC;AAED,oEAIC;AAED,kEAGC;AAED,wEAIC;AAED,sEAGC;AAED,8DAIC;AAED,kEAIC;AAED,0EAIC;AAED,kEAIC;AAED,oEAIC;AAED,0EAIC;AAED,8DAIC;AAED,0DAIC;AAED,sEAIC;AAED,oEAIC;AAED,gFAIC;AAED,0EAIC;AAED,gFAIC;AAED,4EAIC;AAED,gEAGC;AAED,oEAIC;AAED,wDAGC;AAED,0DAGC;AAED,sDAGC;AAED,0DAGC;AAED,gEAIC;AAED,8CAIC;AAED,gDAGC;AAED,kEAGC;AAED,kDAKC;AAED,wDAGC;AAED,0DAQC;AAED,sFAOC;AA/ND,4DAAmC;AASnC,SAAgB,cAAc;IAC5B,OAAO,IAAI,mBAAQ,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC;AAED,SAAgB,gBAAgB;IAC9B,OAAO,IAAI,mBAAQ,CAAC,2CAA2C,EAAE,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAgB,iCAAiC,CAAC,GAAa;IAC7D,MAAM,OAAO,GAC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OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,uBAAuB,CAAC,GAGvC;IACC,MAAM,OAAO,GACX,GAAG,EAAE,IAAI,EAAE,KAAK;QAChB,uEAAuE,CAAC;IAC1E,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,gBAAgB,CAAC,CAAC;AACtE,CAAC;AAED,SAAgB,qCAAqC,CAAC,CAAM;IAC1D,OAAO,IAAI,mBAAQ,CACjB,iCAAiC,EACjC,GAAG,EACH,EAAE,EACF,sBAAsB,CACvB,CAAC;AACJ,CAAC","sourcesContent":["import AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string;\n message: string;\n meta?: Record<string, any>;\n name?: string;\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message =\n err?.message?.split(\"\\n\")[err?.message.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(_: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(_: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(_: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(_: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(message, 409);\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(_: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(_: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(_: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(_: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(_: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(_: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(_: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(_: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(_: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(_: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(_: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as the required record was not found`;\n return new AppError(message, 404, err.meta || {}, \"RecordNotFound\");\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n {},\n \"DatabaseNotAvailable\"\n );\n}\n"]}
|
|
@@ -45,9 +45,10 @@ function ArkosRouter() {
|
|
|
45
45
|
const validationConfig = arkosConfig.validation;
|
|
46
46
|
const authenticationConfig = arkosConfig.authentication;
|
|
47
47
|
if (validationConfig?.strict &&
|
|
48
|
-
"validation" in config
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
(!("validation" in config) ||
|
|
49
|
+
("validation" in config &&
|
|
50
|
+
!config.validation &&
|
|
51
|
+
config.validation !== undefined)))
|
|
51
52
|
throw Error("When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.");
|
|
52
53
|
if (!validationConfig?.resolver && config.validation)
|
|
53
54
|
throw Error("Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })");
|
|
@@ -66,7 +67,8 @@ function ArkosRouter() {
|
|
|
66
67
|
}
|
|
67
68
|
function generateOpenAPIFromApp(app) {
|
|
68
69
|
const routes = (0, helpers_1.extractArkosRoutes)(app);
|
|
69
|
-
|
|
70
|
+
console.log(JSON.stringify(routes, null, 2));
|
|
71
|
+
let paths = {};
|
|
70
72
|
routes.forEach(({ path, method, config }) => {
|
|
71
73
|
if (config?.openapi === false)
|
|
72
74
|
return;
|
|
@@ -85,7 +87,7 @@ function generateOpenAPIFromApp(app) {
|
|
|
85
87
|
summary: openapi?.summary || `${method} ${path}`,
|
|
86
88
|
description: openapi?.description || `${method} ${path}`,
|
|
87
89
|
tags: openapi?.tags || ["Others"],
|
|
88
|
-
operationId: `${method}:${path}`,
|
|
90
|
+
operationId: `${method.toLowerCase()}:${path}`,
|
|
89
91
|
...openapi,
|
|
90
92
|
};
|
|
91
93
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":";;;;;AAkCA,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":";;;;;AAkCA,8BA8EC;AAED,wDAmCC;AArJD,qCAAiC;AAGjC,sFAA4D;AAC5D,oFAA0D;AAC1D,6CAAyE;AACzE,2CAA+C;AAC/C,+DAAyD;AA2BzD,SAAwB,WAAW;IACjC,MAAM,MAAM,GAAiB,IAAA,gBAAM,GAAE,CAAC;IAEtC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;YACxB,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;YAE3D,MAAM,WAAW,GAAG;gBAClB,KAAK;gBACL,MAAM;gBACN,KAAK;gBACL,OAAO;gBACP,QAAQ;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AAM,OAAO,GACX,OAAO,MAAM,EAAE,OAAO,KAAK,QAAQ,IAAI,MAAM,CAAC,OAAO,KAAK,IAAI;YAC5D,CAAC,CAAC,MAAM,CAAC,OAAO;YAChB,CAAC,CAAC,EAAE,CAAC;QAET,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG;YAClC,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YAChD,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YACxD,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,QAAQ,CAAC;YACjC,WAAW,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE;YAC9C,GAAG,OAAO;SACX,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport { extractArkosRoutes, getMiddlewareStack } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * route: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport default function ArkosRouter(): IArkosRouter {\n const router: IArkosRouter = Router();\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n if (httpMethods.includes(prop as string)) {\n return function (\n firstArg: any,\n ...handlers: (ArkosRequestHandler | ArkosErrorRequestHandler)[]\n ) {\n let route = firstArg;\n if (RouteConfigValidator.isArkosRouteConfig(firstArg)) {\n const config = firstArg as ArkosRouteConfig;\n const method = prop as string;\n route = config.route;\n\n if (handlers.length > 0) {\n handlers = handlers.map((handler) =>\n catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n\n if (\n validationConfig?.strict &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })\"\n );\n\n if (!authenticationConfig?.mode && config.authentication)\n throw Error(\n \"Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })\"\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n } else\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig but recevied ${firstArg}`\n );\n\n return originalMethod.call(target, route, ...handlers);\n };\n }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n console.log(JSON.stringify(routes, null, 2));\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config }) => {\n if (config?.openapi === false) return;\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.openapi === \"boolean\") {\n config = {\n ...config,\n openapi: {},\n };\n }\n\n const openapi =\n typeof config?.openapi === \"object\" && config.openapi !== null\n ? config.openapi\n : {};\n\n paths[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${method} ${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Others\"],\n operationId: `${method.toLowerCase()}:${path}`,\n ...openapi,\n };\n });\n\n return paths;\n}\n"]}
|
|
@@ -20,6 +20,7 @@ function extractArkosRoutes(app, basePath = "") {
|
|
|
20
20
|
let config;
|
|
21
21
|
for (const handler of handlers) {
|
|
22
22
|
const foundConfig = route_config_registry_1.default.get(handler.handle);
|
|
23
|
+
console.log(foundConfig, method, layer.route);
|
|
23
24
|
if (foundConfig) {
|
|
24
25
|
config = foundConfig;
|
|
25
26
|
routes.push({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/index.ts"],"names":[],"mappings":";;;;;AAKA,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/index.ts"],"names":[],"mappings":";;;;;AAKA,gDAgEC;AAED,gDAqBC;AA5FD,2DAA2D;AAC3D,gFAAkF;AAClF,wFAA8D;AAG9D,SAAgB,kBAAkB,CAChC,GAAQ,EACR,QAAQ,GAAG,EAAE;IAMb,MAAM,MAAM,GAIP,EAAE,CAAC;IAER,SAAS,gBAAgB,CAAC,KAAY,EAAE,MAAM,GAAG,EAAE;QACjD,KAAK,CAAC,OAAO,CAAC,CAAC,KAAU,EAAE,EAAE;YAC3B,IAAI,KAAK,CAAC,KAAK,EAAE,CA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C,CAAC;wBAC7D,YAAY,GAAG,YAAY;6BACxB,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;6BACrB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;oBACxB,CAAC;gBACH,CAAC;gBAED,gBAAgB,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;YACrD,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,EAAE,KAAK,IAAI,GAAG,CAAC,KAAK,CAAC;IAC9C,IAAI,KAAK;QAAE,gBAAgB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAE7C,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAgB,kBAAkB,CAAC,MAAwB;IACzD,MAAM,WAAW,GAAG,EAAE,CAAC;IACvB,IAAI,MAAM,CAAC,cAAc;QAAE,WAAW,CAAC,IAAI,CAAC,sBAAW,CAAC,YAAY,CAAC,CAAC;IACtE,IACE,OAAO,MAAM,CAAC,cAAc,KAAK,QAAQ;QACzC,MAAM,CAAC,cAAc,CAAC,MAAM;QAC5B,MAAM,CAAC,cAAc,CAAC,QAAQ;QAE9B,WAAW,CAAC,IAAI,CACd,sBAAW,CAAC,mBAAmB,CAC7B,MAAM,CAAC,cAAc,CAAC,MAAM,EAC5B,MAAM,CAAC,cAAc,CAAC,QAAQ,EAC9B;YACE,CAAC,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,cAAc,EAAE,IAAI;SAC5D,CACF,CACF,CAAC;IAEJ,WAAW,CAAC,IAAI,CAAC,IAAA,wCAAqB,EAAC,MAAM,CAAC,CAAC,CAAC;IAEhD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { authService } from \"../../../../exports/services\";\nimport { validateRequestInputs } from \"../../../../modules/base/base.middlewares\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { ArkosRouteConfig } from \"../../types\";\n\nexport function extractArkosRoutes(\n app: any,\n basePath = \"\"\n): Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n}> {\n const routes: Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n }> = [];\n\n function extractFromStack(stack: any[], prefix = \"\") {\n stack.forEach((layer: any) => {\n if (layer.route) {\n const fullPath = prefix + layer.route.path;\n const methods = Object.keys(layer.route.methods);\n\n methods.forEach((method) => {\n const handlers = layer.route.stack || [];\n let config: ArkosRouteConfig | undefined;\n\n for (const handler of handlers) {\n const foundConfig = RouteConfigRegistry.get(handler.handle);\n console.log(foundConfig, method, layer.route);\n\n if (foundConfig) {\n config = foundConfig;\n routes.push({\n path: fullPath,\n method: method.toUpperCase(),\n config,\n });\n\n break;\n }\n }\n });\n } else if (layer.name === \"router\" && layer.handle?.stack) {\n let nestedPrefix = prefix;\n\n if (layer.regexp) {\n const match = layer.regexp\n .toString()\n .match(/\\/\\^?(\\\\\\/[^?]+|\\/[^?]+)/);\n if (match) {\n nestedPrefix = prefix + \"/\" + match[1].replace(/\\\\\\//g, \"/\");\n nestedPrefix = nestedPrefix\n .replace(/\\/\\//g, \"/\")\n .replace(/\\/$/, \"\");\n }\n }\n\n extractFromStack(layer.handle.stack, nestedPrefix);\n }\n });\n }\n\n const stack = app._router?.stack || app.stack;\n if (stack) extractFromStack(stack, basePath);\n\n return routes;\n}\n\nexport function getMiddlewareStack(config: ArkosRouteConfig) {\n const middlewares = [];\n if (config.authentication) middlewares.push(authService.authenticate);\n if (\n typeof config.authentication === \"object\" &&\n config.authentication.action &&\n config.authentication.resource\n )\n middlewares.push(\n authService.handleAccessControl(\n config.authentication.action,\n config.authentication.resource,\n {\n [config.authentication.action]: config.authentication?.rule,\n }\n )\n );\n\n middlewares.push(validateRequestInputs(config));\n\n return middlewares;\n}\n"]}
|
|
@@ -28,7 +28,6 @@ const generateFile = async (options, config) => {
|
|
|
28
28
|
};
|
|
29
29
|
const ext = (0, fs_helpers_1.getUserFileExtension)();
|
|
30
30
|
const resolvedPath = (config.customPath || customPath).replaceAll("{{module-name}}", names.kebab);
|
|
31
|
-
console.log(resolvedPath);
|
|
32
31
|
const modulePath = path_1.default.join(process.cwd(), resolvedPath);
|
|
33
32
|
const fileName = config.prefix
|
|
34
33
|
? `${config.prefix}${names.kebab}.${config.fileSuffix}.${ext}`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.js","sourceRoot":"","sources":["../../../../src/utils/cli/generate.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAoB;AACpB,gDAAwB;AACxB,qEAA+D;AAC/D,qDAA4D;AAC5D,wEAIwC;AACxC,sDAA2E;AAC3E,mDAA2B;AAC3B,0DAAqD;AAgBrD,MAAM,YAAY,GAAG,KAAK,EACxB,OAAwB,EACxB,MAAsB,EACtB,EAAE;IACF,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC;IAEhC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,cAAI,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;QACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAED,IAAI,MAAM,CAAC,gBAAgB;QAAE,MAAM,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC;IAEhE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,6BAA6B,EAAE,GAAG,OAAO,CAAC;IAErE,MAAM,KAAK,GAAG;QACZ,MAAM,EAAE,IAAA,gCAAU,EAAC,SAAS,CAAC;QAC7B,KAAK,EAAE,IAAA,+BAAS,EAAC,SAAS,CAAC;QAC3B,KAAK,EAAE,IAAA,+BAAS,EAAC,SAAS,CAAC;KAC5B,CAAC;IAEF,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;IAEnC,MAAM,YAAY,GAAG,CAAC,MAAM,CAAC,UAAU,IAAI,UAAU,CAAC,CAAC,UAAU,CAC/D,iBAAiB,EACjB,KAAK,CAAC,KAAK,CACZ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E,EAAE;QAC5C,MAAM,YAAY,CAAC,OAAO,EAAE;YAC1B,YAAY,EAAE,YAAY;YAC1B,UAAU,EAAE,KAAK;YACjB,UAAU,EAAE,kCAAkC;YAC9C,MAAM,EAAE,SAAS;SAClB,CAAC,CAAC;IACL,CAAC;IAED,YAAY,EAAE,KAAK,EAAE,OAAwB,EAAE,EAAE;QAC/C,MAAM,YAAY,CAAC,OAAO,EAAE;YAC1B,YAAY,EAAE,eAAe;YAC7B,UAAU,EAAE,OAAO;YACnB,gBAAgB,EAAE,CAAC,SAAS,EAAE,EAAE;gBAC9B,IAAI,SAAS,KAAK,aAAa,EAAE,CAAC;oBAChC,cAAI,CAAC,KAAK,CACR,gEAAgE,CACjE,CAAC;oBACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBAClB,CAAC;YACH,CAAC;SACF,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport { generateTemplate } from \"./utils/template-generators\";\nimport { ensureDirectoryExists } from \"./utils/cli.helpers\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../helpers/change-case.helpers\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport sheu from \"../sheu\";\nimport { capitalize } from \"../helpers/text.helpers\";\n\ninterface GenerateOptions {\n path?: string;\n model: string;\n}\n\ninterface GenerateConfig {\n templateName: string;\n fileSuffix: string;\n customValidation?: (modelName: string) => void;\n customImports?: (names: any) => any;\n customPath?: string;\n prefix?: string;\n}\n\nconst generateFile = async (\n options: GenerateOptions,\n config: GenerateConfig\n) => {\n const modelName = options.model;\n\n if (!modelName) {\n sheu.error(\"Module name is required!\");\n process.exit(1);\n }\n\n if (config.customValidation) config.customValidation(modelName);\n\n const { path: customPath = \"src/modules/{{module-name}}\" } = options;\n\n const names = {\n pascal: pascalCase(modelName),\n camel: camelCase(modelName),\n kebab: kebabCase(modelName),\n };\n\n const ext = getUserFileExtension();\n\n const resolvedPath = (config.customPath || customPath).replaceAll(\n \"{{module-name}}\",\n names.kebab\n );\n console.log(resolvedPath);\n\n const modulePath = path.join(process.cwd(), resolvedPath);\n\n const fileName = config.prefix\n ? `${config.prefix}${names.kebab}.${config.fileSuffix}.${ext}`\n : `${names.kebab}.${config.fileSuffix}.${ext}`;\n\n const filePath = path.join(modulePath, fileName);\n\n const humamReadableTemplateName =\n config.templateName.charAt(0).toUpperCase() +\n config.templateName.slice(1).replaceAll(\"-\", \" \");\n\n try {\n ensureDirectoryExists(modulePath);\n\n const templateData = {\n modelName: names,\n ...(config.customImports && { imports: config.customImports(names) }),\n };\n\n const content = generateTemplate(config.templateName, templateData);\n if (fs.existsSync(filePath))\n throw new Error(\n `${capitalize(humamReadableTemplateName.toLowerCase())} for ${options.model} already exists.`\n );\n fs.writeFileSync(filePath, content);\n\n console.info(\"\");\n sheu.done(\n `${humamReadableTemplateName} for ${options.model} generated under ${fullCleanCwd(filePath)}`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(\n `Failed because of ${err?.message?.toLowerCase() || \"unknown reason\"}`\n );\n process.exit(1);\n }\n};\n\nexport const generateCommand = {\n controller: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"controller\",\n fileSuffix: \"controller\",\n customImports: () => ({\n baseController: \"arkos/controllers\",\n }),\n });\n },\n\n service: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"service\",\n fileSuffix: \"service\",\n customImports: () => ({\n baseService: \"arkos/services\",\n }),\n });\n },\n\n router: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"router\",\n fileSuffix: \"router\",\n customImports: (names) => ({\n baseRouter: \"arkos\",\n controller: `./${names.kebab}.controller`,\n }),\n });\n },\n\n interceptors: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"interceptors\",\n fileSuffix: \"interceptors\",\n });\n },\n\n authConfigs: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"auth-configs\",\n fileSuffix: \"auth\",\n });\n },\n\n hooks: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"hooks\",\n fileSuffix: \"hooks\",\n });\n },\n\n createSchema: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"create-schema\",\n fileSuffix: \"schema\",\n customPath: \"src/modules/{{module-name}}/schemas\",\n prefix: \"create-\",\n });\n },\n\n updateSchema: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"update-schema\",\n fileSuffix: \"schema\",\n customPath: \"src/modules/{{module-name}}/schemas\",\n prefix: \"update-\",\n });\n },\n\n createDto: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"create-dto\",\n fileSuffix: \"dto\",\n customPath: \"src/modules/{{module-name}}/dtos\",\n prefix: \"create-\",\n });\n },\n\n updateDto: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"update-dto\",\n fileSuffix: \"dto\",\n customPath: \"src/modules/{{module-name}}/dtos\",\n prefix: \"update-\",\n });\n },\n\n queryOptions: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"query-options\",\n fileSuffix: \"query\",\n customValidation: (modelName) => {\n if (modelName === \"file-upload\") {\n sheu.error(\n \"Prisma query options are not available to file-upload resource\"\n );\n process.exit(1);\n }\n },\n });\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"generate.js","sourceRoot":"","sources":["../../../../src/utils/cli/generate.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAoB;AACpB,gDAAwB;AACxB,qEAA+D;AAC/D,qDAA4D;AAC5D,wEAIwC;AACxC,sDAA2E;AAC3E,mDAA2B;AAC3B,0DAAqD;AAgBrD,MAAM,YAAY,GAAG,KAAK,EACxB,OAAwB,EACxB,MAAsB,EACtB,EAAE;IACF,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC;IAEhC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,cAAI,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;QACvC,OAAO,CAAC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,EAAE,SAAS;SAClB,CAAC,CAAC;IACL,CAAC;IAED,YAAY,EAAE,KAAK,EAAE,OAAwB,EAAE,EAAE;QAC/C,MAAM,YAAY,CAAC,OAAO,EAAE;YAC1B,YAAY,EAAE,eAAe;YAC7B,UAAU,EAAE,QAAQ;YACpB,UAAU,EAAE,qCAAqC;YACjD,MAAM,EAAE,SAAS;SAClB,CAAC,CAAC;IACL,CAAC;IAED,SAAS,EAAE,KAAK,EAAE,OAAwB,EAAE,EAAE;QAC5C,MAAM,YAAY,CAAC,OAAO,EAAE;YAC1B,YAAY,EAAE,YAAY;YAC1B,UAAU,EAAE,KAAK;YACjB,UAAU,EAAE,kCAAkC;YAC9C,MAAM,EAAE,SAAS;SAClB,CAAC,CAAC;IACL,CAAC;IAED,SAAS,EAAE,KAAK,EAAE,OAAwB,EAAE,EAAE;QAC5C,MAAM,YAAY,CAAC,OAAO,EAAE;YAC1B,YAAY,EAAE,YAAY;YAC1B,UAAU,EAAE,KAAK;YACjB,UAAU,EAAE,kCAAkC;YAC9C,MAAM,EAAE,SAAS;SAClB,CAAC,CAAC;IACL,CAAC;IAED,YAAY,EAAE,KAAK,EAAE,OAAwB,EAAE,EAAE;QAC/C,MAAM,YAAY,CAAC,OAAO,EAAE;YAC1B,YAAY,EAAE,eAAe;YAC7B,UAAU,EAAE,OAAO;YACnB,gBAAgB,EAAE,CAAC,SAAS,EAAE,EAAE;gBAC9B,IAAI,SAAS,KAAK,aAAa,EAAE,CAAC;oBAChC,cAAI,CAAC,KAAK,CACR,gEAAgE,CACjE,CAAC;oBACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBAClB,CAAC;YACH,CAAC;SACF,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport { generateTemplate } from \"./utils/template-generators\";\nimport { ensureDirectoryExists } from \"./utils/cli.helpers\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../helpers/change-case.helpers\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport sheu from \"../sheu\";\nimport { capitalize } from \"../helpers/text.helpers\";\n\ninterface GenerateOptions {\n path?: string;\n model: string;\n}\n\ninterface GenerateConfig {\n templateName: string;\n fileSuffix: string;\n customValidation?: (modelName: string) => void;\n customImports?: (names: any) => any;\n customPath?: string;\n prefix?: string;\n}\n\nconst generateFile = async (\n options: GenerateOptions,\n config: GenerateConfig\n) => {\n const modelName = options.model;\n\n if (!modelName) {\n sheu.error(\"Module name is required!\");\n process.exit(1);\n }\n\n if (config.customValidation) config.customValidation(modelName);\n\n const { path: customPath = \"src/modules/{{module-name}}\" } = options;\n\n const names = {\n pascal: pascalCase(modelName),\n camel: camelCase(modelName),\n kebab: kebabCase(modelName),\n };\n\n const ext = getUserFileExtension();\n\n const resolvedPath = (config.customPath || customPath).replaceAll(\n \"{{module-name}}\",\n names.kebab\n );\n\n const modulePath = path.join(process.cwd(), resolvedPath);\n\n const fileName = config.prefix\n ? `${config.prefix}${names.kebab}.${config.fileSuffix}.${ext}`\n : `${names.kebab}.${config.fileSuffix}.${ext}`;\n\n const filePath = path.join(modulePath, fileName);\n\n const humamReadableTemplateName =\n config.templateName.charAt(0).toUpperCase() +\n config.templateName.slice(1).replaceAll(\"-\", \" \");\n\n try {\n ensureDirectoryExists(modulePath);\n\n const templateData = {\n modelName: names,\n ...(config.customImports && { imports: config.customImports(names) }),\n };\n\n const content = generateTemplate(config.templateName, templateData);\n if (fs.existsSync(filePath))\n throw new Error(\n `${capitalize(humamReadableTemplateName.toLowerCase())} for ${options.model} already exists.`\n );\n fs.writeFileSync(filePath, content);\n\n console.info(\"\");\n sheu.done(\n `${humamReadableTemplateName} for ${options.model} generated under ${fullCleanCwd(filePath)}`\n );\n } catch (err: any) {\n console.info(\"\");\n sheu.error(\n `Failed because of ${err?.message?.toLowerCase() || \"unknown reason\"}`\n );\n process.exit(1);\n }\n};\n\nexport const generateCommand = {\n controller: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"controller\",\n fileSuffix: \"controller\",\n customImports: () => ({\n baseController: \"arkos/controllers\",\n }),\n });\n },\n\n service: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"service\",\n fileSuffix: \"service\",\n customImports: () => ({\n baseService: \"arkos/services\",\n }),\n });\n },\n\n router: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"router\",\n fileSuffix: \"router\",\n customImports: (names) => ({\n baseRouter: \"arkos\",\n controller: `./${names.kebab}.controller`,\n }),\n });\n },\n\n interceptors: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"interceptors\",\n fileSuffix: \"interceptors\",\n });\n },\n\n authConfigs: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"auth-configs\",\n fileSuffix: \"auth\",\n });\n },\n\n hooks: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"hooks\",\n fileSuffix: \"hooks\",\n });\n },\n\n createSchema: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"create-schema\",\n fileSuffix: \"schema\",\n customPath: \"src/modules/{{module-name}}/schemas\",\n prefix: \"create-\",\n });\n },\n\n updateSchema: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"update-schema\",\n fileSuffix: \"schema\",\n customPath: \"src/modules/{{module-name}}/schemas\",\n prefix: \"update-\",\n });\n },\n\n createDto: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"create-dto\",\n fileSuffix: \"dto\",\n customPath: \"src/modules/{{module-name}}/dtos\",\n prefix: \"create-\",\n });\n },\n\n updateDto: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"update-dto\",\n fileSuffix: \"dto\",\n customPath: \"src/modules/{{module-name}}/dtos\",\n prefix: \"update-\",\n });\n },\n\n queryOptions: async (options: GenerateOptions) => {\n await generateFile(options, {\n templateName: \"query-options\",\n fileSuffix: \"query\",\n customValidation: (modelName) => {\n if (modelName === \"file-upload\") {\n sheu.error(\n \"Prisma query options are not available to file-upload resource\"\n );\n process.exit(1);\n }\n },\n });\n },\n};\n"]}
|
package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js
CHANGED
|
@@ -19,6 +19,7 @@ function generateCreateDtoTemplate(options) {
|
|
|
19
19
|
const isUserModule = modelName.kebab === "user";
|
|
20
20
|
const enumsUsed = new Set();
|
|
21
21
|
const validatorsUsed = new Set();
|
|
22
|
+
const transformersUsed = new Set();
|
|
22
23
|
const nestedDtosUsed = new Set();
|
|
23
24
|
let dtoFields = [];
|
|
24
25
|
for (const field of model.fields) {
|
|
@@ -31,13 +32,12 @@ function generateCreateDtoTemplate(options) {
|
|
|
31
32
|
continue;
|
|
32
33
|
const referencedModel = prisma_schema_parser_1.default.models.find((m) => m.name === field.type);
|
|
33
34
|
if (referencedModel) {
|
|
34
|
-
const refField = field.foreignReferenceField || "id";
|
|
35
35
|
const isOptional = field.isOptional || field.defaultValue !== undefined;
|
|
36
36
|
const optionalDecorator = isOptional ? " @IsOptional()\n" : "";
|
|
37
37
|
const typeModifier = isTypeScript ? (isOptional ? "?" : "!") : "";
|
|
38
38
|
validatorsUsed.add("IsOptional");
|
|
39
39
|
validatorsUsed.add("ValidateNested");
|
|
40
|
-
|
|
40
|
+
transformersUsed.add("Type");
|
|
41
41
|
nestedDtosUsed.add("OnlyIdDto");
|
|
42
42
|
dtoFields.push(`${optionalDecorator} @ValidateNested()\n @Type(() => OnlyIdDto)\n ${field.name}${typeModifier}: OnlyIdDto;`);
|
|
43
43
|
}
|
|
@@ -57,7 +57,7 @@ function generateCreateDtoTemplate(options) {
|
|
|
57
57
|
const nestedDtoImports = nestedDtosUsed.size > 0
|
|
58
58
|
? `import { ${Array.from(nestedDtosUsed).join(", ")} } from "../../utils/dtos/only-id-dto.js";\n`
|
|
59
59
|
: "";
|
|
60
|
-
const validatorImports = `import { ${Array.from(validatorsUsed).join(", ")} } from "class-validator";\nimport {
|
|
60
|
+
const validatorImports = `import { ${Array.from(validatorsUsed).join(", ")} } from "class-validator";\nimport { ${Array.from(transformersUsed).join(", ")} } from "class-transformer";\n`;
|
|
61
61
|
return `${validatorImports}${nestedDtoImports}${enumImports}
|
|
62
62
|
export default class Create${modelName.pascal}Dto {
|
|
63
63
|
${dtoFields.join("\n\n")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-dto-template.js","sourceRoot":"","sources":["../../../../../../../../src/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.ts"],"names":[],"mappings":";;;;;AAKA,8DAuFC;AA5FD,sGAA4E;AAE5E,kEAAyE;AAGzE,SAAgB,yBAAyB,CAAC,OAAwB;IAChE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAE9B,IAAI,CAAC,SAAS;QACZ,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IAErE,MAAM,KAAK,GAAG,8BAAkB,CAAC,MAAM,CAAC,IAAI,CAC1C,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,SAAS,CAAC,MAAM,CAAC,WAAW,EAAE,CAC/D,CAAC;IAEF,IAAI,CAAC,KAAK;QACR,MAAM,IAAI,KAAK,CAAC,SAAS,SAAS,CAAC,MAAM,6BAA6B,CAAC,CAAC;IAE1E,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;IACnC,MAAM,YAAY,GAAG,GAAG,KAAK,IAAI,CAAC;IAClC,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;IACvE,MAAM,YAAY,GAAG,SAAS,CAAC,KAAK,KAAK,MAAM,CAAC;IAChD,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IACpC,MAAM,cAAc,GAAG,IAAI,GAAG,EAAU,CAAC;IACzC,MAAM,cAAc,GAAG,IAAI,GAAG,EAAU,CAAC;IAEzC,IAAI,SAAS,GAAa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MAAM;QACR,KAAK,SAAS;YACZ,UAAU,CAAC,IAAI,CAAC,cAAc,SAAS,GAAG,CAAC,CAAC;YAC5C,MAAM;QACR,KAAK,UAAU;YACb,UAAU,CAAC,IAAI,CAAC,WAAW,SAAS,GAAG,CAAC,CAAC;YACzC,MAAM;QACR,KAAK,QAAQ;YACX,UAAU,CAAC,IAAI,CAAC,iBAAiB,SAAS,GAAG,CAAC,CAAC;YAC/C,MAAM;QACR,KAAK,MAAM;YACT,UAAU,CAAC,IAAI,CAAC,aAAa,SAAS,GAAG,CAAC,CAAC;YAC3C,MAAM;QACR;YACE,MAAM;IACV,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,SAAS,iBAAiB,CAAC,UAAkB;IAC3C,QAAQ,UAAU,EAAE,CAAC;QACnB,KAAK,QAAQ;YACX,OAAO,QAAQ,CAAC;QAClB,KAAK,KAAK,CAAC;QACX,KAAK,OAAO,CAAC;QACb,KAAK,SAAS;YACZ,OAAO,QAAQ,CAAC;QAClB,KAAK,SAAS;YACZ,OAAO,SAAS,CAAC;QACnB,KAAK,UAAU;YACb,OAAO,MAAM,CAAC;QAChB,KAAK,MAAM;YACT,OAAO,KAAK,CAAC;QACf,KAAK,OAAO;YACV,OAAO,QAAQ,CAAC;QAClB,KAAK,QAAQ;YACX,OAAO,QAAQ,CAAC;QAClB;YACE,OAAO,KAAK,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["import prismaSchemaParser from \"../../../../../prisma/prisma-schema-parser\";\nimport { PrismaField } from \"../../../../../prisma/types\";\nimport { getUserFileExtension } from \"../../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../../template-generators\";\n\nexport function generateCreateDtoTemplate(options: TemplateOptions): string {\n const { modelName } = options;\n\n if (!modelName)\n throw new Error(\"Module name is required for create-dto template\");\n\n const model = prismaSchemaParser.models.find(\n (m) => m.name.toLowerCase() === modelName.pascal.toLowerCase()\n );\n\n if (!model)\n throw new Error(`Model ${modelName.pascal} not found in Prisma schema`);\n\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n const restrictedFields = [\"id\", \"createdAt\", \"updatedAt\", \"deletedAt\"];\n const isUserModule = modelName.kebab === \"user\";\n const enumsUsed = new Set<string>();\n const validatorsUsed = new Set<string>();\n const nestedDtosUsed = new Set<string>();\n\n let dtoFields: string[] = [];\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (f) => f.foreignKeyField === field.name\n );\n\n if (field.isId || restrictedFields.includes(field.name) || isForeignKey) {\n continue;\n }\n\n if (field.isRelation) {\n if (field.isArray) continue;\n\n const referencedModel = prismaSchemaParser.models.find(\n (m) => m.name === field.type\n );\n\n if (referencedModel) {\n const refField = field.foreignReferenceField || \"id\";\n const isOptional = field.isOptional || field.defaultValue !== undefined;\n const optionalDecorator = isOptional ? \" @IsOptional()\\n\" : \"\";\n const typeModifier = isTypeScript ? (isOptional ? \"?\" : \"!\") : \"\";\n\n validatorsUsed.add(\"IsOptional\");\n validatorsUsed.add(\"ValidateNested\");\n validatorsUsed.add(\"Type\");\n nestedDtosUsed.add(\"OnlyIdDto\");\n\n dtoFields.push(\n `${optionalDecorator} @ValidateNested()\\n @Type(() => OnlyIdDto)\\n ${field.name}${typeModifier}: OnlyIdDto;`\n );\n }\n continue;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n enumsUsed.add(field.type);\n }\n\n const { decorators, type } = generateClassValidatorField(\n field,\n isUserModule,\n validatorsUsed\n );\n const isOptional = field.isOptional || field.defaultValue !== undefined;\n const typeModifier = isTypeScript ? (isOptional ? \"?\" : \"!\") : \"\";\n dtoFields.push(`${decorators} ${field.name}${typeModifier}: ${type};`);\n }\n\n const enumImports =\n enumsUsed.size > 0\n ? `import { ${Array.from(enumsUsed).join(\", \")} } from \"@prisma/client\";\\n`\n : \"\";\n\n const nestedDtoImports =\n nestedDtosUsed.size > 0\n ? `import { ${Array.from(nestedDtosUsed).join(\", \")} } from \"../../utils/dtos/only-id-dto\";\\n`\n : \"\";\n\n const validatorImports = `import { ${Array.from(validatorsUsed).join(\", \")} } from \"class-validator\";\\nimport { Type } from \"class-transformer\";\\n`;\n\n return `${validatorImports}${nestedDtoImports}${enumImports}\nexport default class Create${modelName.pascal}Dto {\n${dtoFields.join(\"\\n\\n\")}\n}`;\n}\n\nfunction generateClassValidatorField(\n field: PrismaField,\n isUserModule: boolean,\n validatorsUsed: Set<string>\n): { decorators: string; type: string } {\n let decorators: string[] = [];\n let type = mapPrismaTypeToTS(field.type);\n\n const isOptional = field.isOptional || field.defaultValue !== undefined;\n if (isOptional) {\n decorators.push(\"@IsOptional()\");\n validatorsUsed.add(\"IsOptional\");\n }\n\n if (field.isArray) {\n decorators.push(\"@IsArray()\");\n validatorsUsed.add(\"IsArray\");\n type = `${type}[]`;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n decorators.push(\n `@IsEnum(${field.type}${field.isArray ? \", { each: true }\" : \"\"})`\n );\n validatorsUsed.add(\"IsEnum\");\n type = field.isArray ? `${field.type}[]` : field.type;\n } else {\n const fieldValidators = getValidatorsForType(field, isUserModule);\n decorators.push(...fieldValidators);\n fieldValidators.forEach((decorator) => {\n const validatorName = decorator.match(/@(\\w+)/)?.[1];\n if (validatorName) validatorsUsed.add(validatorName);\n });\n }\n\n return {\n decorators:\n decorators.map((d) => ` ${d}`).join(\"\\n\") +\n (decorators.length > 0 ? \"\\n\" : \"\"),\n type,\n };\n}\n\nfunction getValidatorsForType(\n field: PrismaField,\n isUserModule: boolean\n): string[] {\n const validators: string[] = [];\n const arrayEach = field.isArray ? \", { each: true }\" : \"\";\n\n if (isUserModule) {\n if (field.name === \"email\") {\n return [\"@IsEmail()\"];\n } else if (field.name === \"password\") {\n return [\n \"@IsString()\",\n \"@MinLength(8)\",\n '@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)/, { message: \"Password must contain at least one uppercase letter, one lowercase letter, and one number\" })',\n ];\n }\n }\n\n switch (field.type) {\n case \"String\":\n validators.push(`@IsString(${arrayEach})`);\n break;\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n validators.push(`@IsNumber({}, ${arrayEach})`);\n break;\n case \"Boolean\":\n validators.push(`@IsBoolean(${arrayEach})`);\n break;\n case \"DateTime\":\n validators.push(`@IsDate(${arrayEach})`);\n break;\n case \"BigInt\":\n validators.push(`@IsNumber({}, ${arrayEach})`);\n break;\n case \"Json\":\n validators.push(`@IsObject(${arrayEach})`);\n break;\n default:\n break;\n }\n\n return validators;\n}\n\nfunction mapPrismaTypeToTS(prismaType: string): string {\n switch (prismaType) {\n case \"String\":\n return \"string\";\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n return \"number\";\n case \"Boolean\":\n return \"boolean\";\n case \"DateTime\":\n return \"Date\";\n case \"Json\":\n return \"any\";\n case \"Bytes\":\n return \"Buffer\";\n case \"BigInt\":\n return \"bigint\";\n default:\n return \"any\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create-dto-template.js","sourceRoot":"","sources":["../../../../../../../../src/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.ts"],"names":[],"mappings":";;;;;AAKA,8DAuFC;AA5FD,sGAA4E;AAE5E,kEAAyE;AAGzE,SAAgB,yBAAyB,CAAC,OAAwB;IAChE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAE9B,IAAI,CAAC,SAAS;QACZ,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IAErE,MAAM,KAAK,GAAG,8BAAkB,CAAC,MAAM,CAAC,IAAI,CAC1C,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,SAAS,CAAC,MAAM,CAAC,WAAW,EAAE,CAC/D,CAAC;IAEF,IAAI,CAAC,KAAK;QACR,MAAM,IAAI,KAAK,CAAC,SAAS,SAAS,CAAC,MAAM,6BAA6B,CAAC,CAAC;IAE1E,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE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AAK,QAAQ;YACX,OAAO,QAAQ,CAAC;QAClB;YACE,OAAO,KAAK,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["import prismaSchemaParser from \"../../../../../prisma/prisma-schema-parser\";\nimport { PrismaField } from \"../../../../../prisma/types\";\nimport { getUserFileExtension } from \"../../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../../template-generators\";\n\nexport function generateCreateDtoTemplate(options: TemplateOptions): string {\n const { modelName } = options;\n\n if (!modelName)\n throw new Error(\"Module name is required for create-dto template\");\n\n const model = prismaSchemaParser.models.find(\n (m) => m.name.toLowerCase() === modelName.pascal.toLowerCase()\n );\n\n if (!model)\n throw new Error(`Model ${modelName.pascal} not found in Prisma schema`);\n\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n const restrictedFields = [\"id\", \"createdAt\", \"updatedAt\", \"deletedAt\"];\n const isUserModule = modelName.kebab === \"user\";\n const enumsUsed = new Set<string>();\n const validatorsUsed = new Set<string>();\n const transformersUsed = new Set<string>();\n const nestedDtosUsed = new Set<string>();\n\n let dtoFields: string[] = [];\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (f) => f.foreignKeyField === field.name\n );\n\n if (field.isId || restrictedFields.includes(field.name) || isForeignKey) {\n continue;\n }\n\n if (field.isRelation) {\n if (field.isArray) continue;\n\n const referencedModel = prismaSchemaParser.models.find(\n (m) => m.name === field.type\n );\n\n if (referencedModel) {\n const isOptional = field.isOptional || field.defaultValue !== undefined;\n const optionalDecorator = isOptional ? \" @IsOptional()\\n\" : \"\";\n const typeModifier = isTypeScript ? (isOptional ? \"?\" : \"!\") : \"\";\n\n validatorsUsed.add(\"IsOptional\");\n validatorsUsed.add(\"ValidateNested\");\n transformersUsed.add(\"Type\");\n nestedDtosUsed.add(\"OnlyIdDto\");\n\n dtoFields.push(\n `${optionalDecorator} @ValidateNested()\\n @Type(() => OnlyIdDto)\\n ${field.name}${typeModifier}: OnlyIdDto;`\n );\n }\n continue;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n enumsUsed.add(field.type);\n }\n\n const { decorators, type } = generateClassValidatorField(\n field,\n isUserModule,\n validatorsUsed\n );\n const isOptional = field.isOptional || field.defaultValue !== undefined;\n const typeModifier = isTypeScript ? (isOptional ? \"?\" : \"!\") : \"\";\n dtoFields.push(`${decorators} ${field.name}${typeModifier}: ${type};`);\n }\n\n const enumImports =\n enumsUsed.size > 0\n ? `import { ${Array.from(enumsUsed).join(\", \")} } from \"@prisma/client\";\\n`\n : \"\";\n\n const nestedDtoImports =\n nestedDtosUsed.size > 0\n ? `import { ${Array.from(nestedDtosUsed).join(\", \")} } from \"../../utils/dtos/only-id-dto\";\\n`\n : \"\";\n\n const validatorImports = `import { ${Array.from(validatorsUsed).join(\", \")} } from \"class-validator\";\\nimport { ${Array.from(transformersUsed).join(\", \")} } from \"class-transformer\";\\n`;\n\n return `${validatorImports}${nestedDtoImports}${enumImports}\nexport default class Create${modelName.pascal}Dto {\n${dtoFields.join(\"\\n\\n\")}\n}`;\n}\n\nfunction generateClassValidatorField(\n field: PrismaField,\n isUserModule: boolean,\n validatorsUsed: Set<string>\n): { decorators: string; type: string } {\n let decorators: string[] = [];\n let type = mapPrismaTypeToTS(field.type);\n\n const isOptional = field.isOptional || field.defaultValue !== undefined;\n if (isOptional) {\n decorators.push(\"@IsOptional()\");\n validatorsUsed.add(\"IsOptional\");\n }\n\n if (field.isArray) {\n decorators.push(\"@IsArray()\");\n validatorsUsed.add(\"IsArray\");\n type = `${type}[]`;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n decorators.push(\n `@IsEnum(${field.type}${field.isArray ? \", { each: true }\" : \"\"})`\n );\n validatorsUsed.add(\"IsEnum\");\n type = field.isArray ? `${field.type}[]` : field.type;\n } else {\n const fieldValidators = getValidatorsForType(field, isUserModule);\n decorators.push(...fieldValidators);\n fieldValidators.forEach((decorator) => {\n const validatorName = decorator.match(/@(\\w+)/)?.[1];\n if (validatorName) validatorsUsed.add(validatorName);\n });\n }\n\n return {\n decorators:\n decorators.map((d) => ` ${d}`).join(\"\\n\") +\n (decorators.length > 0 ? \"\\n\" : \"\"),\n type,\n };\n}\n\nfunction getValidatorsForType(\n field: PrismaField,\n isUserModule: boolean\n): string[] {\n const validators: string[] = [];\n const arrayEach = field.isArray ? \", { each: true }\" : \"\";\n\n if (isUserModule) {\n if (field.name === \"email\") {\n return [\"@IsEmail()\"];\n } else if (field.name === \"password\") {\n return [\n \"@IsString()\",\n \"@MinLength(8)\",\n '@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)/, { message: \"Password must contain at least one uppercase letter, one lowercase letter, and one number\" })',\n ];\n }\n }\n\n switch (field.type) {\n case \"String\":\n validators.push(`@IsString(${arrayEach})`);\n break;\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n validators.push(`@IsNumber({}, ${arrayEach})`);\n break;\n case \"Boolean\":\n validators.push(`@IsBoolean(${arrayEach})`);\n break;\n case \"DateTime\":\n validators.push(`@IsDate(${arrayEach})`);\n break;\n case \"BigInt\":\n validators.push(`@IsNumber({}, ${arrayEach})`);\n break;\n case \"Json\":\n validators.push(`@IsObject(${arrayEach})`);\n break;\n default:\n break;\n }\n\n return validators;\n}\n\nfunction mapPrismaTypeToTS(prismaType: string): string {\n switch (prismaType) {\n case \"String\":\n return \"string\";\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n return \"number\";\n case \"Boolean\":\n return \"boolean\";\n case \"DateTime\":\n return \"Date\";\n case \"Json\":\n return \"any\";\n case \"Bytes\":\n return \"Buffer\";\n case \"BigInt\":\n return \"bigint\";\n default:\n return \"any\";\n }\n}\n"]}
|
package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js
CHANGED
|
@@ -19,6 +19,7 @@ function generateUpdateDtoTemplate(options) {
|
|
|
19
19
|
const isUserModule = modelName.kebab === "user";
|
|
20
20
|
const enumsUsed = new Set();
|
|
21
21
|
const validatorsUsed = new Set();
|
|
22
|
+
const transformersUsed = new Set();
|
|
22
23
|
const nestedDtosUsed = new Set();
|
|
23
24
|
let dtoFields = [];
|
|
24
25
|
for (const field of model.fields) {
|
|
@@ -34,7 +35,7 @@ function generateUpdateDtoTemplate(options) {
|
|
|
34
35
|
const typeModifier = isTypeScript ? "?" : "";
|
|
35
36
|
validatorsUsed.add("IsOptional");
|
|
36
37
|
validatorsUsed.add("ValidateNested");
|
|
37
|
-
|
|
38
|
+
transformersUsed.add("Type");
|
|
38
39
|
nestedDtosUsed.add("OnlyIdDto");
|
|
39
40
|
dtoFields.push(` @IsOptional()\n @ValidateNested()\n @Type(() => OnlyIdDto)\n ${field.name}${typeModifier}: OnlyIdDto;`);
|
|
40
41
|
}
|
|
@@ -53,7 +54,7 @@ function generateUpdateDtoTemplate(options) {
|
|
|
53
54
|
const nestedDtoImports = nestedDtosUsed.size > 0
|
|
54
55
|
? `import { ${Array.from(nestedDtosUsed).join(", ")} } from "../../utils/dtos/only-id-dto.js";\n`
|
|
55
56
|
: "";
|
|
56
|
-
const validatorImports = `import { ${Array.from(validatorsUsed).join(", ")} } from "class-validator";\nimport {
|
|
57
|
+
const validatorImports = `import { ${Array.from(validatorsUsed).join(", ")} } from "class-validator";\nimport { ${Array.from(transformersUsed).join(", ")} } from "class-transformer";\n`;
|
|
57
58
|
return `${validatorImports}${nestedDtoImports}${enumImports}
|
|
58
59
|
export default class Update${modelName.pascal}Dto {
|
|
59
60
|
${dtoFields.join("\n\n")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update-dto-template.js","sourceRoot":"","sources":["../../../../../../../../src/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.ts"],"names":[],"mappings":";;;;;AAKA,8DAkFC;AAvFD,sGAA4E;AAE5E,kEAAyE;AAGzE,SAAgB,yBAAyB,CAAC,OAAwB;IAChE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAE9B,IAAI,CAAC,SAAS;QACZ,MAAM,IAAI,KAAK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chemaParser from \"../../../../../prisma/prisma-schema-parser\";\nimport { PrismaField } from \"../../../../../prisma/types\";\nimport { getUserFileExtension } from \"../../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../../template-generators\";\n\nexport function generateUpdateDtoTemplate(options: TemplateOptions): string {\n const { modelName } = options;\n\n if (!modelName)\n throw new Error(\"Module name is required for update-dto template\");\n\n const model = prismaSchemaParser.models.find(\n (m) => m.name.toLowerCase() === modelName.pascal.toLowerCase()\n );\n\n if (!model)\n throw new Error(`Model ${modelName.pascal} not found in Prisma schema`);\n\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n const restrictedFields = [\"id\", \"createdAt\", \"updatedAt\", \"deletedAt\"];\n const isUserModule = modelName.kebab === \"user\";\n const enumsUsed = new Set<string>();\n const validatorsUsed = new Set<string>();\n const nestedDtosUsed = new Set<string>();\n\n let dtoFields: string[] = [];\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (f) => f.foreignKeyField === field.name\n );\n\n if (field.isId || restrictedFields.includes(field.name) || isForeignKey) {\n continue;\n }\n\n if (field.isRelation) {\n if (field.isArray) continue;\n\n const referencedModel = prismaSchemaParser.models.find(\n (m) => m.name === field.type\n );\n\n if (referencedModel) {\n const typeModifier = isTypeScript ? \"?\" : \"\";\n validatorsUsed.add(\"IsOptional\");\n validatorsUsed.add(\"ValidateNested\");\n validatorsUsed.add(\"Type\");\n nestedDtosUsed.add(\"OnlyIdDto\");\n\n dtoFields.push(\n ` @IsOptional()\\n @ValidateNested()\\n @Type(() => OnlyIdDto)\\n ${field.name}${typeModifier}: OnlyIdDto;`\n );\n }\n continue;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n enumsUsed.add(field.type);\n }\n\n const { decorators, type } = generateClassValidatorField(\n field,\n isUserModule,\n validatorsUsed\n );\n const typeModifier = isTypeScript ? \"?\" : \"\";\n dtoFields.push(`${decorators} ${field.name}${typeModifier}: ${type};`);\n }\n\n const enumImports =\n enumsUsed.size > 0\n ? `import { ${Array.from(enumsUsed).join(\", \")} } from \"@prisma/client\";\\n`\n : \"\";\n\n const nestedDtoImports =\n nestedDtosUsed.size > 0\n ? `import { ${Array.from(nestedDtosUsed).join(\", \")} } from \"../../utils/dtos/only-id-dto\";\\n`\n : \"\";\n\n const validatorImports = `import { ${Array.from(validatorsUsed).join(\", \")} } from \"class-validator\";\\nimport { Type } from \"class-transformer\";\\n`;\n\n return `${validatorImports}${nestedDtoImports}${enumImports}\nexport default class Update${modelName.pascal}Dto {\n${dtoFields.join(\"\\n\\n\")}\n}`;\n}\n\nfunction generateClassValidatorField(\n field: PrismaField,\n isUserModule: boolean,\n validatorsUsed: Set<string>\n): { decorators: string; type: string } {\n let decorators: string[] = [];\n let type = mapPrismaTypeToTS(field.type);\n\n // All fields in update DTO are optional\n decorators.push(\"@IsOptional()\");\n validatorsUsed.add(\"IsOptional\");\n\n if (field.isArray) {\n decorators.push(\"@IsArray()\");\n validatorsUsed.add(\"IsArray\");\n type = `${type}[]`;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n decorators.push(\n `@IsEnum(${field.type}${field.isArray ? \", { each: true }\" : \"\"})`\n );\n validatorsUsed.add(\"IsEnum\");\n type = field.isArray ? `${field.type}[]` : field.type;\n } else {\n const fieldValidators = getValidatorsForType(field, isUserModule);\n decorators.push(...fieldValidators);\n fieldValidators.forEach((decorator) => {\n const validatorName = decorator.match(/@(\\w+)/)?.[1];\n if (validatorName) validatorsUsed.add(validatorName);\n });\n }\n\n return {\n decorators:\n decorators.map((d) => ` ${d}`).join(\"\\n\") +\n (decorators.length > 0 ? \"\\n\" : \"\"),\n type,\n };\n}\n\nfunction getValidatorsForType(\n field: PrismaField,\n isUserModule: boolean\n): string[] {\n const validators: string[] = [];\n\n if (isUserModule) {\n if (field.name === \"email\") {\n return [\"@IsEmail()\"];\n } else if (field.name === \"password\") {\n return [\n \"@IsString()\",\n \"@MinLength(8)\",\n '@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)/, { message: \"Password must contain at least one uppercase letter, one lowercase letter, and one number\" })',\n ];\n }\n }\n\n switch (field.type) {\n case \"String\":\n validators.push(\n field.isArray ? \"@IsString({ each: true })\" : \"@IsString()\"\n );\n break;\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n validators.push(\n field.isArray ? \"@IsNumber({}, { each: true })\" : \"@IsNumber()\"\n );\n break;\n case \"Boolean\":\n validators.push(\n field.isArray ? \"@IsBoolean({ each: true })\" : \"@IsBoolean()\"\n );\n break;\n case \"DateTime\":\n validators.push(field.isArray ? \"@IsDate({ each: true })\" : \"@IsDate()\");\n break;\n case \"BigInt\":\n validators.push(\n field.isArray ? \"@IsNumber({}, { each: true })\" : \"@IsNumber()\"\n );\n break;\n case \"Json\":\n validators.push(\n field.isArray ? \"@IsObject({ each: true })\" : \"@IsObject()\"\n );\n break;\n default:\n break;\n }\n\n return validators;\n}\n\nfunction mapPrismaTypeToTS(prismaType: string): string {\n switch (prismaType) {\n case \"String\":\n return \"string\";\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n return \"number\";\n case \"Boolean\":\n return \"boolean\";\n case \"DateTime\":\n return \"Date\";\n case \"Json\":\n return \"any\";\n case \"Bytes\":\n return \"Buffer\";\n case \"BigInt\":\n return \"bigint\";\n default:\n return \"any\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"update-dto-template.js","sourceRoot":"","sources":["../../../../../../../../src/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.ts"],"names":[],"mappings":";;;;;AAKA,8DAmFC;AAxFD,sGAA4E;AAE5E,kEAAyE;AAGzE,SAAgB,yBAAyB,CAAC,OAAwB;IAChE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAE9B,IAAI,CAAC,SAAS;QACZ,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IAErE,MAAM,KAAK,GAAG,8BAAkB,CAAC,MAAM,CAAC,IAAI,CAC1C,CAAC,CAAC,E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ACH,CAAC","sourcesContent":["import prismaSchemaParser from \"../../../../../prisma/prisma-schema-parser\";\nimport { PrismaField } from \"../../../../../prisma/types\";\nimport { getUserFileExtension } from \"../../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../../template-generators\";\n\nexport function generateUpdateDtoTemplate(options: TemplateOptions): string {\n const { modelName } = options;\n\n if (!modelName)\n throw new Error(\"Module name is required for update-dto template\");\n\n const model = prismaSchemaParser.models.find(\n (m) => m.name.toLowerCase() === modelName.pascal.toLowerCase()\n );\n\n if (!model)\n throw new Error(`Model ${modelName.pascal} not found in Prisma schema`);\n\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n const restrictedFields = [\"id\", \"createdAt\", \"updatedAt\", \"deletedAt\"];\n const isUserModule = modelName.kebab === \"user\";\n const enumsUsed = new Set<string>();\n const validatorsUsed = new Set<string>();\n const transformersUsed = new Set<string>();\n const nestedDtosUsed = new Set<string>();\n\n let dtoFields: string[] = [];\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (f) => f.foreignKeyField === field.name\n );\n\n if (field.isId || restrictedFields.includes(field.name) || isForeignKey) {\n continue;\n }\n\n if (field.isRelation) {\n if (field.isArray) continue;\n\n const referencedModel = prismaSchemaParser.models.find(\n (m) => m.name === field.type\n );\n\n if (referencedModel) {\n const typeModifier = isTypeScript ? \"?\" : \"\";\n validatorsUsed.add(\"IsOptional\");\n validatorsUsed.add(\"ValidateNested\");\n transformersUsed.add(\"Type\");\n nestedDtosUsed.add(\"OnlyIdDto\");\n\n dtoFields.push(\n ` @IsOptional()\\n @ValidateNested()\\n @Type(() => OnlyIdDto)\\n ${field.name}${typeModifier}: OnlyIdDto;`\n );\n }\n continue;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n enumsUsed.add(field.type);\n }\n\n const { decorators, type } = generateClassValidatorField(\n field,\n isUserModule,\n validatorsUsed\n );\n const typeModifier = isTypeScript ? \"?\" : \"\";\n dtoFields.push(`${decorators} ${field.name}${typeModifier}: ${type};`);\n }\n\n const enumImports =\n enumsUsed.size > 0\n ? `import { ${Array.from(enumsUsed).join(\", \")} } from \"@prisma/client\";\\n`\n : \"\";\n\n const nestedDtoImports =\n nestedDtosUsed.size > 0\n ? `import { ${Array.from(nestedDtosUsed).join(\", \")} } from \"../../utils/dtos/only-id-dto\";\\n`\n : \"\";\n\n const validatorImports = `import { ${Array.from(validatorsUsed).join(\", \")} } from \"class-validator\";\\nimport { ${Array.from(transformersUsed).join(\", \")} } from \"class-transformer\";\\n`;\n\n return `${validatorImports}${nestedDtoImports}${enumImports}\nexport default class Update${modelName.pascal}Dto {\n${dtoFields.join(\"\\n\\n\")}\n}`;\n}\n\nfunction generateClassValidatorField(\n field: PrismaField,\n isUserModule: boolean,\n validatorsUsed: Set<string>\n): { decorators: string; type: string } {\n let decorators: string[] = [];\n let type = mapPrismaTypeToTS(field.type);\n\n // All fields in update DTO are optional\n decorators.push(\"@IsOptional()\");\n validatorsUsed.add(\"IsOptional\");\n\n if (field.isArray) {\n decorators.push(\"@IsArray()\");\n validatorsUsed.add(\"IsArray\");\n type = `${type}[]`;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n decorators.push(\n `@IsEnum(${field.type}${field.isArray ? \", { each: true }\" : \"\"})`\n );\n validatorsUsed.add(\"IsEnum\");\n type = field.isArray ? `${field.type}[]` : field.type;\n } else {\n const fieldValidators = getValidatorsForType(field, isUserModule);\n decorators.push(...fieldValidators);\n fieldValidators.forEach((decorator) => {\n const validatorName = decorator.match(/@(\\w+)/)?.[1];\n if (validatorName) validatorsUsed.add(validatorName);\n });\n }\n\n return {\n decorators:\n decorators.map((d) => ` ${d}`).join(\"\\n\") +\n (decorators.length > 0 ? \"\\n\" : \"\"),\n type,\n };\n}\n\nfunction getValidatorsForType(\n field: PrismaField,\n isUserModule: boolean\n): string[] {\n const validators: string[] = [];\n\n if (isUserModule) {\n if (field.name === \"email\") {\n return [\"@IsEmail()\"];\n } else if (field.name === \"password\") {\n return [\n \"@IsString()\",\n \"@MinLength(8)\",\n '@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)/, { message: \"Password must contain at least one uppercase letter, one lowercase letter, and one number\" })',\n ];\n }\n }\n\n switch (field.type) {\n case \"String\":\n validators.push(\n field.isArray ? \"@IsString({ each: true })\" : \"@IsString()\"\n );\n break;\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n validators.push(\n field.isArray ? \"@IsNumber({}, { each: true })\" : \"@IsNumber()\"\n );\n break;\n case \"Boolean\":\n validators.push(\n field.isArray ? \"@IsBoolean({ each: true })\" : \"@IsBoolean()\"\n );\n break;\n case \"DateTime\":\n validators.push(field.isArray ? \"@IsDate({ each: true })\" : \"@IsDate()\");\n break;\n case \"BigInt\":\n validators.push(\n field.isArray ? \"@IsNumber({}, { each: true })\" : \"@IsNumber()\"\n );\n break;\n case \"Json\":\n validators.push(\n field.isArray ? \"@IsObject({ each: true })\" : \"@IsObject()\"\n );\n break;\n default:\n break;\n }\n\n return validators;\n}\n\nfunction mapPrismaTypeToTS(prismaType: string): string {\n switch (prismaType) {\n case \"String\":\n return \"string\";\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n return \"number\";\n case \"Boolean\":\n return \"boolean\";\n case \"DateTime\":\n return \"Date\";\n case \"Json\":\n return \"any\";\n case \"Bytes\":\n return \"Buffer\";\n case \"BigInt\":\n return \"bigint\";\n default:\n return \"any\";\n }\n}\n"]}
|
|
@@ -85,7 +85,7 @@ function sendProductionError(err, req, res) {
|
|
|
85
85
|
}
|
|
86
86
|
res.status(err.statusCode).json({
|
|
87
87
|
title: "Internal server error",
|
|
88
|
-
message: "
|
|
88
|
+
message: "Internal server error, please try again later.",
|
|
89
89
|
});
|
|
90
90
|
}
|
|
91
91
|
process.on("SIGTERM", () => {
|