arkos 1.2.29-test → 1.2.31-test
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/auth/auth.router.js +9 -83
- package/dist/cjs/modules/auth/auth.router.js.map +1 -1
- package/dist/cjs/modules/base/base.service.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +10 -94
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +2 -0
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/catch-async.js +1 -1
- package/dist/cjs/modules/error-handler/utils/catch-async.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +6 -0
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/cjs/modules/file-upload/file-upload.router.js +9 -21
- package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/cjs/modules/file-upload/utils/helpers/file-upload.helpers.js +7 -0
- package/dist/cjs/modules/file-upload/utils/helpers/file-upload.helpers.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js +3 -2
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
- package/dist/cjs/server.js +2 -2
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +16 -14
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/generate.js +1 -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/generate-service-template.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-service-template.js.map +1 -1
- package/dist/cjs/utils/features/api.features.js +9 -3
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/cjs/utils/helpers/global.helpers.js +7 -19
- package/dist/cjs/utils/helpers/global.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +20 -8
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js +7 -4
- package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/routers.helpers.js +21 -0
- package/dist/cjs/utils/helpers/routers.helpers.js.map +1 -0
- package/dist/cjs/utils/sheu.js +101 -125
- package/dist/cjs/utils/sheu.js.map +1 -1
- package/dist/esm/modules/auth/auth.router.js +9 -83
- package/dist/esm/modules/auth/auth.router.js.map +1 -1
- package/dist/esm/modules/base/base.service.js.map +1 -1
- package/dist/esm/modules/base/utils/helpers/base.router.helpers.js +10 -94
- package/dist/esm/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +2 -0
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/catch-async.js +1 -1
- package/dist/esm/modules/error-handler/utils/catch-async.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +5 -0
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/esm/modules/file-upload/file-upload.router.js +9 -21
- package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/esm/modules/file-upload/utils/helpers/file-upload.helpers.js +6 -0
- package/dist/esm/modules/file-upload/utils/helpers/file-upload.helpers.js.map +1 -1
- package/dist/esm/modules/swagger/swagger.router.js +1 -1
- package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js +3 -2
- package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
- package/dist/esm/server.js +2 -2
- package/dist/esm/server.js.map +1 -1
- package/dist/esm/utils/cli/dev.js +16 -14
- package/dist/esm/utils/cli/dev.js.map +1 -1
- package/dist/esm/utils/cli/generate.js +1 -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/generate-service-template.js +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-service-template.js.map +1 -1
- package/dist/esm/utils/features/api.features.js +9 -3
- package/dist/esm/utils/features/api.features.js.map +1 -1
- package/dist/esm/utils/helpers/global.helpers.js +7 -19
- package/dist/esm/utils/helpers/global.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/models.helpers.js +19 -8
- package/dist/esm/utils/helpers/models.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/prisma.helpers.js +7 -4
- package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/routers.helpers.js +16 -0
- package/dist/esm/utils/helpers/routers.helpers.js.map +1 -0
- package/dist/esm/utils/sheu.js +101 -125
- package/dist/esm/utils/sheu.js.map +1 -1
- package/dist/types/modules/auth/auth.controller.d.ts +7 -7
- package/dist/types/modules/auth/auth.service.d.ts +1 -1
- package/dist/types/modules/base/base.controller.d.ts +9 -9
- package/dist/types/modules/base/base.service.d.ts +1 -1
- package/dist/types/modules/error-handler/utils/catch-async.d.ts +2 -1
- package/dist/types/modules/error-handler/utils/error-handler.helpers.d.ts +4 -0
- package/dist/types/modules/file-upload/file-upload.controller.d.ts +4 -4
- package/dist/types/modules/file-upload/file-upload.router.d.ts +1 -1
- package/dist/types/modules/file-upload/utils/helpers/file-upload.helpers.d.ts +2 -1
- package/dist/types/modules/swagger/utils/helpers/swagger.router.helpers.d.ts +1 -1
- package/dist/types/utils/features/api.features.d.ts +1 -0
- package/dist/types/utils/helpers/models.helpers.d.ts +7 -4
- package/dist/types/utils/helpers/prisma.helpers.d.ts +1 -1
- package/dist/types/utils/helpers/routers.helpers.d.ts +2 -0
- package/dist/types/utils/sheu.d.ts +66 -21
- package/package.json +2 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAgEC;AAnFD,kEAAyC;AACzC,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,IAAkB;IAElB,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;IAGnC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC1C,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;QACpC,OAAO;IACT,CAAC;IAGD,IAAI,KAAK,GAAG,EAAE,GAAG,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,CAAC;IAG7C,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,EAAE,CAAC;IAGnD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B;QAC5C,KAAK,GAAG,qBAAqB,CAAC,iCAAiC,CAAC,GAAG,CAAC,CAAC;IAGvE,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO;QACtB,KAAK,GAAG,qBAAqB,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC;IAC/D,IAAI,G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GAAG,CAAC,OAAO;gBACpB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE;gBACpB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,SAAS;aAC5B,CAAC,CAAC;;YAEH,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACnB,MAAM,EAAE,OAAO;gBACf,OAAO,EAAE,uBAAuB;aACjC,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,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,yBAAyB;KACnC,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} next - 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 next: NextFunction\n): void {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\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\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 === \"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 if (!error.isOperational) error = new AppError(\"Something went wrong!\", 500);\n\n // Send the error response for production environment\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: \"Something went wrong!\",\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: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\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,+BAkEC;AArFD,kEAAyC;AACzC,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,IAAkB;IAElB,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;IAGnC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC1C,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;QACpC,OAAO;IACT,CAAC;IAGD,IAAI,KAAK,GAAG,EAAE,GAAG,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,CAAC;IAG7C,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EA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,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} next - 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 next: NextFunction\n): void {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\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\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 if (!error.isOperational) error = new AppError(\"Something went wrong!\", 500);\n\n // Send the error response for production environment\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: \"Something went wrong!\",\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: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catch-async.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/catch-async.ts"],"names":[],"mappings":";;AAwBA,MAAM,UAAU,GACd,CAAC,EAAuB,EAAE,EAAE,CAC5B,KAAK,
|
|
1
|
+
{"version":3,"file":"catch-async.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/catch-async.ts"],"names":[],"mappings":";;AAwBA,MAAM,UAAU,GACd,CAAC,EAAuB,EAAE,EAAE,CAC5B,KAAK,EACH,GAAiB,EACjB,GAAkB,EAClB,IAAuB,EACR,EAAE;IACjB,IAAI,CAAC;QACH,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAS,CAAC;IAC5C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,GAAG,CAAC,CAAC;IACZ,CAAC;AACH,CAAC,CAAC;AAIJ,kBAAe,UAAU,CAAC","sourcesContent":["import {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../../types\";\n\n/**\n * Used to wrap request handlers and middleware for automatic catch async errors and throw to next to invoke the global error handler\n *\n * @param {ArkosRequestHandler} fn - an express request handler or middleware that will be called with req, res, next, with catch attached for error handling\n * @returns\n *\n * @example\n * ```typescript\n * import { ArkosRequest, ArkosResponse, ArkosNextFunction } from 'arkos'\n *\n * export const getManyPosts = catchAsync(async\n * (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n * const posts = await getSomePosts()\n * res.status(200).json({ data: posts })\n * })\n * ```\n */\nconst catchAsync =\n (fn: ArkosRequestHandler) =>\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ): Promise<void> => {\n try {\n return (await fn(req, res, next)) as void;\n } catch (err) {\n next(err);\n }\n };\n\nexport type CatchAsyncReturnType = ReturnType<typeof catchAsync>;\n\nexport default catchAsync;\n"]}
|
|
@@ -38,6 +38,7 @@ exports.handleNetworkError = handleNetworkError;
|
|
|
38
38
|
exports.handleUnhandledPromiseError = handleUnhandledPromiseError;
|
|
39
39
|
exports.handleDataTypeError = handleDataTypeError;
|
|
40
40
|
exports.handleEmptyResultError = handleEmptyResultError;
|
|
41
|
+
exports.handleNonExistingRecord = handleNonExistingRecord;
|
|
41
42
|
const app_error_1 = __importDefault(require("./app-error"));
|
|
42
43
|
function handleJWTError() {
|
|
43
44
|
return new app_error_1.default("Invalid token. Please log in again!", 401);
|
|
@@ -192,4 +193,9 @@ function handleEmptyResultError(err) {
|
|
|
192
193
|
const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;
|
|
193
194
|
return new app_error_1.default(message, 404);
|
|
194
195
|
}
|
|
196
|
+
function handleNonExistingRecord(err) {
|
|
197
|
+
const message = err?.meta?.cause ||
|
|
198
|
+
`Operation could not be completed as the required record was not found`;
|
|
199
|
+
return new app_error_1.default(message, 404, err.meta || {}, "PrismaRecordNotFound");
|
|
200
|
+
}
|
|
195
201
|
//# sourceMappingURL=error-handler.helpers.js.map
|
|
@@ -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,8EAGC;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;AA3MD,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,GAAG,GAAG,EAAE,OAAO,CAAC,KA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OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,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 = err?.message.split(\"\\n\")[err?.message.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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"]}
|
|
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,8EAGC;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;AArND,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,GAAG,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC9E,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,yBAAyB,CAAC,GAAa;IACrD,MAAM,OAAO,GACX,mFAAmF,CAAC;IACtF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AAC5E,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 = err?.message.split(\"\\n\")[err?.message.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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(err: 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 || {}, \"PrismaRecordNotFound\");\n}\n"]}
|
|
@@ -12,9 +12,12 @@ const path_1 = __importDefault(require("path"));
|
|
|
12
12
|
const express_2 = __importDefault(require("express"));
|
|
13
13
|
const deepmerge_helper_1 = __importDefault(require("../../utils/helpers/deepmerge.helper"));
|
|
14
14
|
const base_middlewares_1 = require("../base/base.middlewares");
|
|
15
|
+
const routers_helpers_1 = require("../../utils/helpers/routers.helpers");
|
|
16
|
+
const file_upload_helpers_1 = require("./utils/helpers/file-upload.helpers");
|
|
15
17
|
const router = (0, express_1.Router)();
|
|
16
|
-
async function getFileUploadRouter(
|
|
17
|
-
const
|
|
18
|
+
async function getFileUploadRouter(arkosConfig) {
|
|
19
|
+
const { fileUpload } = arkosConfig;
|
|
20
|
+
const modelModules = await (0, models_helpers_1.importPrismaModelModules)("file-upload", arkosConfig);
|
|
18
21
|
let { middlewares = {}, authConfigs = {} } = {};
|
|
19
22
|
if (modelModules) {
|
|
20
23
|
({ middlewares = {}, authConfigs = {} } = modelModules);
|
|
@@ -24,10 +27,7 @@ async function getFileUploadRouter({ fileUpload }) {
|
|
|
24
27
|
basePathname = "/" + basePathname;
|
|
25
28
|
if (!basePathname.endsWith("/"))
|
|
26
29
|
basePathname = basePathname + "/";
|
|
27
|
-
router.get(`${basePathname}*`, auth_service_1.default.handleAuthenticationControl("View", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("View", "file-upload", authConfigs.accessControl), ...(middlewares?.beforeFindFile
|
|
28
|
-
req.url = req.url.replace(basePathname, "/");
|
|
29
|
-
next();
|
|
30
|
-
}, express_2.default.static(path_1.default.resolve(process.cwd(), fileUpload?.baseUploadDir || "uploads"), (0, deepmerge_helper_1.default)({
|
|
30
|
+
router.get(`${basePathname}*`, auth_service_1.default.handleAuthenticationControl("View", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("View", "file-upload", authConfigs.accessControl), ...(0, routers_helpers_1.processMiddleware)(middlewares?.beforeFindFile), file_upload_helpers_1.adjustRequestUrl, express_2.default.static(path_1.default.resolve(process.cwd(), fileUpload?.baseUploadDir || "uploads"), (0, deepmerge_helper_1.default)({
|
|
31
31
|
maxAge: "1y",
|
|
32
32
|
etag: true,
|
|
33
33
|
lastModified: true,
|
|
@@ -36,21 +36,9 @@ async function getFileUploadRouter({ fileUpload }) {
|
|
|
36
36
|
index: false,
|
|
37
37
|
cacheControl: true,
|
|
38
38
|
}, fileUpload?.expressStaticOptions || {})));
|
|
39
|
-
router.post(`${basePathname}:fileType`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("Create", "file-upload", authConfigs.accessControl), middlewares?.beforeUploadFile
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
? middlewares?.afterUploadFile
|
|
43
|
-
: base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
|
|
44
|
-
router.patch(`${basePathname}:fileType/:fileName`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("Update", "file-upload", authConfigs.accessControl), middlewares?.beforeUpdateFile || file_upload_controller_1.default.updateFile, middlewares?.beforeUpdateFile
|
|
45
|
-
? file_upload_controller_1.default.updateFile
|
|
46
|
-
: middlewares?.afterUpdateFile || base_middlewares_1.sendResponse, middlewares?.beforeUpdateFile && middlewares?.afterUpdateFile
|
|
47
|
-
? middlewares?.afterUpdateFile
|
|
48
|
-
: base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
|
|
49
|
-
router.delete(`${basePathname}:fileType/:fileName`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("Delete", "file-upload", authConfigs.accessControl), middlewares?.beforeDeleteFile || file_upload_controller_1.default.deleteFile, middlewares?.beforeDeleteFile
|
|
50
|
-
? file_upload_controller_1.default.deleteFile
|
|
51
|
-
: middlewares?.afterDeleteFile || base_middlewares_1.sendResponse, middlewares?.beforeDeleteFile && middlewares?.afterDeleteFile
|
|
52
|
-
? middlewares?.afterDeleteFile
|
|
53
|
-
: base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
|
|
39
|
+
router.post(`${basePathname}:fileType`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("Create", "file-upload", authConfigs.accessControl), ...(0, routers_helpers_1.processMiddleware)(middlewares?.beforeUploadFile), file_upload_controller_1.default.uploadFile, ...(0, routers_helpers_1.processMiddleware)(middlewares?.afterUploadFile), base_middlewares_1.sendResponse);
|
|
40
|
+
router.patch(`${basePathname}:fileType/:fileName`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("Update", "file-upload", authConfigs.accessControl), ...(0, routers_helpers_1.processMiddleware)(middlewares?.beforeUpdateFile), file_upload_controller_1.default.updateFile, ...(0, routers_helpers_1.processMiddleware)(middlewares?.afterUpdateFile), base_middlewares_1.sendResponse);
|
|
41
|
+
router.delete(`${basePathname}:fileType/:fileName`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("Delete", "file-upload", authConfigs.accessControl), ...(0, routers_helpers_1.processMiddleware)(middlewares?.beforeDeleteFile), file_upload_controller_1.default.deleteFile, ...(0, routers_helpers_1.processMiddleware)(middlewares?.afterDeleteFile), base_middlewares_1.sendResponse);
|
|
54
42
|
return router;
|
|
55
43
|
}
|
|
56
44
|
//# sourceMappingURL=file-upload.router.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AAeA,kDAwGC;AAvHD,qCAAiC;AACjC,uEAA8E;AAC9E,wEAA+C;AAC/C,sFAA4D;AAE5D,gDAAwB;AACxB,sDAA8B;AAC9B,4FAA6D;AAE7D,+DAAwD;AACxD,yEAAwE;AACxE,6EAAuE;AAEvE,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;AAEzB,KAAK,UAAU,mBAAmB,CAAC,WAAwB;IAChE,MAAM,EAAE,UAAU,EAAE,GAAG,WAAW,CAAC;IAEnC,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EACjD,aAAa,EACb,WAAW,CACZ,CAAC;IACF,IAAI,EAAE,WAAW,GAAG,EAAS,EAAE,WAAW,GAAG,EAAiB,EAAE,GAAG,EAAE,CAAC;IAEtE,IAAI,YAAY,EAAE,CAAC;QACjB,CAAC,EAAE,WAAW,GAAG,EAAE,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,YAAY,CAAC,CAAC;IAC1D,CAAC;IAED,IAAI,YAAY,GAAG,UAAU,EAAE,SAAS,IAAI,eAAe,CAAC;IAE5D,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,YAAY,GAAG,GAAG,GAAG,YAAY,CAAC;IACrE,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,YAAY,GAAG,YAAY,GAAG,GAAG,CAAC;IAGnE,MAAM,CAAC,GAAG,CACR,GAAG,YAAY,GAAG,EAClB,sBAAW,CAAC,2BAA2B,CACrC,MAAM,EACN,WAAW,CAAC,qBAAqB,CAClC,EACD,sBAAW,CAAC,mBAAmB,CAC7B,MAAM,EACN,aAAa,EACb,WAAW,CAAC,aAAa,CAC1B,EACD,GAAG,IAAA,mCAAiB,EAAC,WAAW,EAAE,cAAc,CAAC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,CAAC,qBAAqB,CAClC,EACD,sBAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,aAAa,EACb,WAAW,CAAC,aAAa,CAC1B,EACD,GAAG,IAAA,mCAAiB,EAAC,WAAW,EAAE,gBAAgB,CAAC,EACnD,gCAAoB,CAAC,UAAU,EAC/B,GAAG,IAAA,mCAAiB,EAAC,WAAW,EAAE,eAAe,CAAC,EAClD,+BAAY,CACb,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport authService from \"../auth/auth.service\";\nimport fileUploadController from \"./file-upload.controller\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport path from \"path\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { sendResponse } from \"../base/base.middlewares\";\nimport { processMiddleware } from \"../../utils/helpers/routers.helpers\";\nimport { adjustRequestUrl } from \"./utils/helpers/file-upload.helpers\";\n\nconst router: Router = Router();\n\nexport async function getFileUploadRouter(arkosConfig: ArkosConfig) {\n const { fileUpload } = arkosConfig;\n\n const modelModules = await importPrismaModelModules(\n \"file-upload\",\n arkosConfig\n );\n let { middlewares = {} as any, authConfigs = {} as AuthConfigs } = {};\n\n if (modelModules) {\n ({ middlewares = {}, authConfigs = {} } = modelModules);\n }\n\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n // Static file serving route\n router.get(\n `${basePathname}*`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(middlewares?.beforeFindFile),\n adjustRequestUrl,\n express.static(\n path.resolve(process.cwd(), fileUpload?.baseUploadDir || \"uploads\"),\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStaticOptions || {}\n )\n )\n );\n\n // POST /{basePathname}:fileType - Upload File\n router.post(\n `${basePathname}:fileType`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(middlewares?.beforeUploadFile),\n fileUploadController.uploadFile,\n ...processMiddleware(middlewares?.afterUploadFile),\n sendResponse\n );\n\n // PATCH /{basePathname}:fileType/:fileName - Update File\n router.patch(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(middlewares?.beforeUpdateFile),\n fileUploadController.updateFile,\n ...processMiddleware(middlewares?.afterUpdateFile),\n sendResponse\n );\n\n // DELETE /{basePathname}:fileType/:fileName - Delete File\n router.delete(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(middlewares?.beforeDeleteFile),\n fileUploadController.deleteFile,\n ...processMiddleware(middlewares?.afterDeleteFile),\n sendResponse\n );\n\n return router;\n}\n"]}
|
|
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.processImage = exports.processFile = void 0;
|
|
7
|
+
exports.adjustRequestUrl = adjustRequestUrl;
|
|
7
8
|
exports.extractRequestInfo = extractRequestInfo;
|
|
8
9
|
const fs_1 = __importDefault(require("fs"));
|
|
9
10
|
const path_1 = __importDefault(require("path"));
|
|
@@ -12,6 +13,12 @@ const util_1 = require("util");
|
|
|
12
13
|
const server_1 = require("../../../../server");
|
|
13
14
|
const mimetype_1 = __importDefault(require("mimetype"));
|
|
14
15
|
const fs_helpers_1 = require("../../../../utils/helpers/fs.helpers");
|
|
16
|
+
function adjustRequestUrl(req, _, next) {
|
|
17
|
+
const { fileUpload } = (0, server_1.getArkosConfig)();
|
|
18
|
+
req.url = req.url.replace(fileUpload?.baseRoute + "/" || "/api/uploads/", "/");
|
|
19
|
+
req.url = req.url.replace(fileUpload?.baseRoute || "/api/uploads/", "/");
|
|
20
|
+
next();
|
|
21
|
+
}
|
|
15
22
|
function extractRequestInfo(req) {
|
|
16
23
|
const { fileUpload } = (0, server_1.getArkosConfig)();
|
|
17
24
|
const protocol = req.headers["x-forwarded-proto"] === "https" ? "https" : "http";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-upload.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/file-upload/utils/helpers/file-upload.helpers.ts"],"names":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"file-upload.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/file-upload/utils/helpers/file-upload.helpers.ts"],"names":[],"mappings":";;;;;;AAaA,4CAYC;AAED,gDASC;AApCD,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,+BAAiC;AACjC,+CAAoD;AACpD,wDAAgC;AAMhC,qEAAoE;AAEpE,SAAgB,gBAAgB,CAC9B,GAAiB,EACjB,CAAgB,EAChB,IAAuB;IAEvB,MAAM,EAAE,UAAU,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;IACxC,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CACvB,UAAU,EAAE,SAAS,GAAG,GAAG,IAAI,eAAe,EAC9C,GAAG,CACJ,CAAC;IACF,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,CAA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AC;QAC7C,CAAC;QAGD,MAAM,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAGnC,MAAM,IAAA,gBAAS,EAAC,YAAE,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QAG/C,MAAM,YAAY,GAAG,oBAAoB,CAAC,QAAQ,EAAE,GAAG,EAAE,MAAO,CAAC,QAAQ,CAAC,CAAC;QAE3E,OAAO,GAAG,OAAO,GAAG,SAAS,IAAI,YAAY,EAAE,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAEf,IAAI,CAAC;YACH,MAAM,IAAA,gBAAS,EAAC,YAAE,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC;YACnC,MAAM,IAAA,gBAAS,EAAC,YAAE,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;QAEf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC,CAAC;AArEW,QAAA,YAAY,gBAqEvB","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport sharp from \"sharp\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../../../server\";\nimport mimetype from \"mimetype\";\nimport {\n ArkosNextFunction,\n ArkosRequest,\n ArkosResponse,\n} from \"../../../../types\";\nimport { fullCleanCwd } from \"../../../../utils/helpers/fs.helpers\";\n\nexport function adjustRequestUrl(\n req: ArkosRequest,\n _: ArkosResponse,\n next: ArkosNextFunction\n) {\n const { fileUpload } = getArkosConfig();\n req.url = req.url.replace(\n fileUpload?.baseRoute + \"/\" || \"/api/uploads/\",\n \"/\"\n );\n req.url = req.url.replace(fileUpload?.baseRoute || \"/api/uploads/\", \"/\");\n next();\n}\n\nexport function extractRequestInfo(req: ArkosRequest) {\n const { fileUpload } = getArkosConfig();\n\n // Determine the base URL for file access\n const protocol =\n req.headers[\"x-forwarded-proto\"] === \"https\" ? \"https\" : \"http\";\n const baseURL = `${protocol}://${req.get?.(\"host\")}`;\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n return { baseURL, baseRoute };\n}\n\n/**\n * Generates the correct relative path regardless of upload directory location\n */\nconst generateRelativePath = (filePath: string, fileType: string) => {\n const { fileUpload } = getArkosConfig();\n\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n if (baseUploadDir.startsWith(\"..\")) {\n // For paths outside project directory\n return path.join(fileType, path.basename(filePath));\n } else {\n // For paths within project\n return fullCleanCwd(\n filePath\n .replace(`${baseUploadDir}/`, \"\")\n .replace(`/${baseUploadDir}/`, \"\")\n .replace(`/${baseUploadDir}`, \"\")\n .replace(`${baseUploadDir}`, \"\")\n );\n }\n};\n\n/**\n * Handles basic file processing for non-image files\n */\nexport const processFile = async (\n req: ArkosRequest,\n filePath: string\n): Promise<string> => {\n const { baseURL, baseRoute } = extractRequestInfo(req);\n\n const relativePath = generateRelativePath(filePath, req.params!.fileType);\n return `${baseURL}${baseRoute === \"/\" ? \"\" : baseRoute}/${relativePath}`;\n};\n\n/**\n * Processes image files using Sharp for resizing and format conversion\n */\nexport const processImage = async (\n req: ArkosRequest,\n filePath: string,\n options: Record<string, any>\n): Promise<string | null> => {\n const { baseURL, baseRoute } = extractRequestInfo(req);\n\n const ext = path.extname(filePath).toLowerCase();\n const originalFormat = ext.replace(\".\", \"\");\n const outputFormat = options.format || originalFormat;\n\n if (!mimetype.lookup(ext)?.includes?.(\"image\")) {\n const relativePath = generateRelativePath(filePath, req.params!.fileType);\n return `${baseURL}${baseRoute}/${relativePath}`;\n }\n\n // Create a temp filename with original name + random string\n const tempName = `${path.basename(filePath, ext)}_${Date.now()}${ext}`;\n const tempPath = path.join(path.dirname(filePath), tempName);\n\n try {\n let transformer = sharp(filePath);\n const metadata = await transformer.metadata();\n\n // Apply resize transformations if requested\n if (options.resizeTo && metadata.width && metadata.height) {\n const targetSize = options.resizeTo;\n const scaleFactor =\n targetSize / Math.min(metadata.width, metadata.height);\n const newWidth = Math.round(metadata.width * scaleFactor);\n const newHeight = Math.round(metadata.height * scaleFactor);\n transformer = transformer.resize(newWidth, newHeight);\n } else if (options.width || options.height) {\n transformer = transformer.resize(\n options.width || null,\n options.height || null,\n {\n fit: \"inside\",\n }\n );\n }\n\n // Apply format transformations if requested\n if (outputFormat === \"webp\") {\n transformer = transformer.toFormat(\"webp\");\n } else if (outputFormat === \"jpeg\" || outputFormat === \"jpg\") {\n transformer = transformer.toFormat(\"jpeg\");\n }\n\n // Save to temp file first\n await transformer.toFile(tempPath);\n\n // Rename temp file to original filename\n await promisify(fs.rename)(tempPath, filePath);\n\n // Return the public URL for the file\n const relativePath = generateRelativePath(filePath, req?.params!.fileType);\n\n return `${baseURL}${baseRoute}/${relativePath}`;\n } catch (error) {\n // Clean up temp file if it exists\n try {\n await promisify(fs.stat)(tempPath);\n await promisify(fs.unlink)(tempPath);\n } catch (err) {\n // If temp file doesn't exist, no need to clean up\n }\n throw error;\n }\n};\n"]}
|
|
@@ -12,7 +12,7 @@ const swagger_router_helpers_1 = require("./utils/helpers/swagger.router.helpers
|
|
|
12
12
|
const swaggerRouter = (0, express_1.Router)();
|
|
13
13
|
async function getSwaggerRouter(arkosConfig) {
|
|
14
14
|
const defaultJsonSchemas = await (0, swagger_router_helpers_1.getOpenAPIJsonSchemasByConfigMode)(arkosConfig.swagger);
|
|
15
|
-
const defaultModelsPaths = await (0, swagger_router_helpers_1.generatePathsForModels)(arkosConfig
|
|
15
|
+
const defaultModelsPaths = await (0, swagger_router_helpers_1.generatePathsForModels)(arkosConfig);
|
|
16
16
|
const defaultSwaggerConfig = {
|
|
17
17
|
endpoint: "/api-docs",
|
|
18
18
|
mode: "prisma",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAYA,4CA8IC;AA1JD,qCAAiC;AACjC,4EAA2C;AAC3C,kEAAyC;AAEzC,4FAA6D;AAC7D,mFAGgD;AAEhD,MAAM,aAAa,GAAG,IAAA,gBAAM,GAAE,CAAC;AAExB,KAAK,UAAU,gBAAgB,CACpC,WAAwB;IAExB,MAAM,kBAAkB,GAAG,MAAM,IAAA,0DAAiC,EAChE,WAAW,CAAC,OAAO,CACpB,CAAC;IACF,MAAM,kBAAkB,GAAG,MAAM,IAAA,+CAAsB,EAAC,WAAW,CAAC,
|
|
1
|
+
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAYA,4CA8IC;AA1JD,qCAAiC;AACjC,4EAA2C;AAC3C,kEAAyC;AAEzC,4FAA6D;AAC7D,mFAGgD;AAEhD,MAAM,aAAa,GAAG,IAAA,gBAAM,GAAE,CAAC;AAExB,KAAK,UAAU,gBAAgB,CACpC,WAAwB;IAExB,MAAM,kBAAkB,GAAG,MAAM,IAAA,0DAAiC,EAChE,WAAW,CAAC,OAAO,CACpB,CAAC;IACF,MAAM,kBAAkB,GAAG,MAAM,IAAA,+CAAsB,EAAC,WAAW,CAAC,CAAC;IAErE,MAAM,oBAAoB,GAA2B;QACnD,QAAQ,EAAE,WAAW;QACrB,IAAI,EAAE,QAAQ;QACd,OAAO,EAAE;YACP,UAAU,EAAE;gBACV,OAAO,EAAE,OAAO;gBAChB,IAAI,EAAE;oBACJ,KAAK,EAAE,qBAAqB;oBAC5B,OAAO,EAAE,OAAO;oBAChB,WAAW,EACT,sFAAsF;iBACzF;gBACD,OAAO,EAAE;oBACP;wBACE,GAAG,EAAE,UAAU,WAAW,CAAC,IAAI,IAAI,WAAW,CAAC,IAAI,EAAE;wBACrD,WAAW,EAAE,oBAAoB;qBAClC;iBACF;gBACD,KAAK,EAAE,kBAAkB;gBACzB,UAAU,EAAE;oBACV,OAAO,EAAE,kBAAkB,IAAI,EAAE;oBACjC,eAAe,EAAE;wBACf,UAAU,EAAE;4BACV,IAAI,E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AO,CAAC,gBAAgB,EAAE,aAAa;QACrE,cAAc,EAAE;YACd,MAAM,EACJ,cAAc,CAAC,OAAO,CAAC,gBAAgB,EAAE,cAAc,EAAE,MAAM,IAAI,IAAI;YACzE,sBAAsB,EACpB,cAAc,CAAC,OAAO,CAAC,gBAAgB,EAAE,cAAc;gBACrD,EAAE,sBAAsB,IAAI,IAAI;YACpC,WAAW,EAAE,cAAc,CAAC,OAAO,CAAC,WAAW,IAAI,IAAI;YACvD,eAAe,EAAE,cAAc,CAAC,OAAO,CAAC,eAAe,IAAI,IAAI;YAC/D,oBAAoB,EAClB,cAAc,CAAC,OAAO,CAAC,oBAAoB,IAAI,KAAK;YACtD,cAAc,EACZ,cAAc,CAAC,OAAO,CAAC,gBAAgB,EAAE,cAAc;gBACrD,EAAE,cAAc,IAAI,IAAI;YAC5B,oBAAoB,EAClB,cAAc,CAAC,OAAO,CAAC,gBAAgB,EAAE,cAAc;gBACrD,EAAE,oBAAoB,IAAI,IAAI;YAClC,GAAG,cAAc,CAAC,OAAO,CAAC,gBAAgB,EAAE,cAAc;SAC3D;KACF,CAAC;IAGF,aAAa,CAAC,GAAG,CAAC,cAAc,CAAC,QAAS,EAAE,4BAAS,CAAC,KAAK,CAAC,CAAC;IAG7D,aAAa,CAAC,GAAG,CACf,cAAc,CAAC,QAAS,EACxB,4BAAS,CAAC,KAAK,CAAC,oBAAoB,EAAE,gBAAgB,CAAC,CACxD,CAAC;IA4BF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport swaggerUi from \"swagger-ui-express\";\nimport swaggerJsdoc from \"swagger-jsdoc\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport {\n generatePathsForModels,\n getOpenAPIJsonSchemasByConfigMode,\n} from \"./utils/helpers/swagger.router.helpers\";\n\nconst swaggerRouter = Router();\n\nexport async function getSwaggerRouter(\n arkosConfig: ArkosConfig\n): Promise<Router> {\n const defaultJsonSchemas = await getOpenAPIJsonSchemasByConfigMode(\n arkosConfig.swagger\n );\n const defaultModelsPaths = await generatePathsForModels(arkosConfig);\n\n const defaultSwaggerConfig: ArkosConfig[\"swagger\"] = {\n endpoint: \"/api-docs\",\n mode: \"prisma\",\n options: {\n definition: {\n openapi: \"3.0.0\",\n info: {\n title: \"Powered By Arkos.js\",\n version: \"1.0.0\",\n description:\n \"This API was automatically generated by Arkos.js, read more about at www.arkosjs.com\",\n },\n servers: [\n {\n url: `http://${arkosConfig.host}:${arkosConfig.port}`,\n description: \"Development server\",\n },\n ],\n paths: defaultModelsPaths,\n components: {\n schemas: defaultJsonSchemas || {},\n securitySchemes: {\n BearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n },\n },\n },\n security: [],\n },\n apis: [\n \"./src/routers/*.router.{ts,js}\",\n \"./src/modules/**/*.router.{ts,js}\",\n ],\n swaggerUiOptions: {\n explorer: true,\n swaggerOptions: {\n filter: true,\n displayRequestDuration: true,\n showExtensions: true,\n showCommonExtensions: true,\n },\n },\n deepLinking: true,\n tryItOutEnabled: true,\n persistAuthorization: false,\n },\n };\n\n // Merge default config with user config\n const swaggerConfigs = deepmerge(\n defaultSwaggerConfig,\n arkosConfig.swagger || {}\n );\n\n // Merge mode-generated schemas with existing schemas\n if (swaggerConfigs?.options?.definition?.components?.schemas) {\n swaggerConfigs.options.definition.components.schemas = {\n ...swaggerConfigs?.options?.definition?.components.schemas,\n };\n }\n\n // Generate OpenAPI specification using swagger-jsdoc\n const swaggerSpecification = swaggerJsdoc({\n definition: swaggerConfigs.options\n .definition as swaggerJsdoc.SwaggerDefinition,\n apis: swaggerConfigs.options.apis || [],\n });\n\n // Setup Swagger UI options\n const swaggerUiOptions = {\n explorer: swaggerConfigs.options.swaggerUiOptions?.explorer ?? true,\n customCss: swaggerConfigs.options.swaggerUiOptions?.customCss,\n customSiteTitle:\n swaggerConfigs.options.swaggerUiOptions?.customSiteTitle ||\n \"Arkos.js API Documentation\",\n customfavIcon: swaggerConfigs.options.swaggerUiOptions?.customfavIcon,\n swaggerOptions: {\n filter:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions?.filter ?? true,\n displayRequestDuration:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions\n ?.displayRequestDuration ?? true,\n deepLinking: swaggerConfigs.options.deepLinking ?? true,\n tryItOutEnabled: swaggerConfigs.options.tryItOutEnabled ?? true,\n persistAuthorization:\n swaggerConfigs.options.persistAuthorization ?? false,\n showExtensions:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions\n ?.showExtensions ?? true,\n showCommonExtensions:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions\n ?.showCommonExtensions ?? true,\n ...swaggerConfigs.options.swaggerUiOptions?.swaggerOptions,\n },\n };\n\n // Serve Swagger UI static assets\n swaggerRouter.use(swaggerConfigs.endpoint!, swaggerUi.serve);\n\n // Serve Swagger documentation\n swaggerRouter.get(\n swaggerConfigs.endpoint!,\n swaggerUi.setup(swaggerSpecification, swaggerUiOptions)\n );\n\n // Serve raw OpenAPI spec as JSON\n // swaggerRouter.get(`${swaggerConfigs.endpoint}/json`, (req, res) => {\n // res.setHeader(\"Content-Type\", \"application/json\");\n // res.json(swaggerSpecification);\n // });\n\n // // Serve raw OpenAPI spec as YAML (optional)\n // swaggerRouter.get(`${swaggerConfigs.endpoint}/yaml`, (req, res) => {\n // const yaml = require(\"js-yaml\");\n // res.setHeader(\"Content-Type\", \"text/yaml\");\n // res.send(yaml.dump(swaggerSpecification));\n // });\n\n // // Health check endpoint for Swagger itself\n // swaggerRouter.get(`${swaggerConfigs.endpoint}/health`, (req, res) => {\n // res.json({\n // status: \"ok\",\n // swagger: {\n // version: swaggerConfigs?.options?.definition?.openapi,\n // title: swaggerConfigs?.options?.definition?.info?.title,\n // endpoint: swaggerConfigs.endpoint,\n // mode: swaggerConfigs.mode,\n // },\n // });\n // });\n\n return swaggerRouter;\n}\n"]}
|
|
@@ -66,7 +66,8 @@ function getSchemaRef(schemaName, mode) {
|
|
|
66
66
|
return `#/components/schemas/${schemaName}`;
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
|
-
async function generatePathsForModels(
|
|
69
|
+
async function generatePathsForModels(arkosConfig) {
|
|
70
|
+
const swaggerConfig = arkosConfig?.swagger;
|
|
70
71
|
if (!swaggerConfig)
|
|
71
72
|
return {};
|
|
72
73
|
let paths = {};
|
|
@@ -78,7 +79,7 @@ async function generatePathsForModels(swaggerConfig) {
|
|
|
78
79
|
const pascalModelName = (0, utils_1.pascalCase)(model);
|
|
79
80
|
const humanReadableName = kebabToHuman(modelName);
|
|
80
81
|
const humanReadableNamePlural = pluralize_1.default.plural(humanReadableName);
|
|
81
|
-
const modelModules = await (0, models_helpers_1.importPrismaModelModules)(model);
|
|
82
|
+
const modelModules = await (0, models_helpers_1.importPrismaModelModules)(model, arkosConfig);
|
|
82
83
|
const routerConfig = modelModules.router?.config;
|
|
83
84
|
if (routerConfig?.disable === true)
|
|
84
85
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swagger.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/swagger.router.helpers.ts"],"names":[],"mappings":";;;;;AAgBA,8EAeC;AAED,4DAwBC;AAED,oCAKC;AAED,oCAUC;AAED,
|
|
1
|
+
{"version":3,"file":"swagger.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/swagger.router.helpers.ts"],"names":[],"mappings":";;;;;AAgBA,8EAeC;AAED,4DAwBC;AAED,oCAKC;AAED,oCAUC;AAED,wDAwDC;AArID,6EAGkD;AAClD,qDAAkE;AAElE,0DAAkC;AAClC,iFAA0E;AAC1E,iGAA0F;AAC1F,gGAA2F;AAC3F,0HAAmH;AACnH,wGAAkG;AAClG,gIAA8H;AAC9H,oIAAiI;AAE1H,KAAK,UAAU,iCAAiC,CACrD,aAAqC;IAErC,QAAQ,aAAc,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,uBAAuB,EACvB,YAAY,EACZ,IAAI,CACL,CAAC;QAGF,IAAI,YAAY,EAAE,MAAM;YACtB,MAAM,IAAA,yEAAmC,EACvC,KAAK,EACL,SAAS,EACT,eAAe,EACf,iBAAiB,EACjB,uBAAuB,EACvB,YAAY,EACZ,IAAI,CACL,CAAC;IACN,CAAC;IAGD,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,GAAG,IAAA,uDAAwB,GAAE,EAAE,CAAC;IAGpD,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,GAAG,IAAA,uEAAgC,GAAE,EAAE,CAAC;IAE5D,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { ArkosConfig } from \"../../../../exports\";\nimport {\n getModels,\n importPrismaModelModules,\n} from \"../../../../utils/helpers/models.helpers\";\nimport { kebabCase, pascalCase } from \"../../../../exports/utils\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport pluralize from \"pluralize\";\nimport { getSystemJsonSchemaPaths } from \"./get-system-json-schema-paths\";\nimport { getAuthenticationJsonSchemaPaths } from \"./get-authentication-json-schema-paths\";\nimport { generateZodJsonSchemas } from \"./json-schema-generators/generate-zod-json-schema\";\nimport { generateClassValidatorJsonSchemas } from \"./json-schema-generators/generate-class-validator-json-schemas\";\nimport { generatePrismaJsonSchemas } from \"./json-schema-generators/generate-prisma-json-schemas\";\nimport { generatePrismaModelMainRoutesPaths } from \"./json-schema-generators/prisma-models/generate-prisma-model-main-routes\";\nimport { generatePrismaModelParentRoutePaths } from \"./json-schema-generators/prisma-models/generate-prisma-model-parent-routes\";\n\nexport async function getOpenAPIJsonSchemasByConfigMode(\n swaggerConfig: ArkosConfig[\"swagger\"]\n) {\n switch (swaggerConfig!.mode) {\n case \"prisma\":\n return await generatePrismaJsonSchemas();\n case \"class-validator\":\n return await generateClassValidatorJsonSchemas();\n case \"zod\":\n return await generateZodJsonSchemas();\n default:\n throw Error(\n \"Unknown mode for auto documentation, supported values are prisma, class-validator, zod or json-schemas\"\n );\n }\n}\n\nexport function getCorrectJsonSchemaName(\n type: string,\n modelName: string,\n suffix: \"Dto\" | \"Schema\"\n): string {\n const pascalModelName = pascalCase(modelName);\n\n const map: Record<string, string> = {\n model: pascalModelName,\n create: `Create${pascalModelName}`,\n createMany: `CreateMany${pascalModelName}`,\n findOne: `FindOne${pascalModelName}`,\n findMany: `FindMany${pascalModelName}`,\n update: `Update${pascalModelName}`,\n updateMany: `UpdateMany${pascalModelName}`,\n query: `Query${pascalModelName}`,\n login: \"Login\",\n signup: \"Signup\",\n updateMe: \"UpdateMe\",\n updatePassword: \"UpdatePassword\",\n };\n\n const baseName = map[type] ?? pascalCase(type);\n return `${baseName}${suffix}`;\n}\n\nexport function kebabToHuman(kebabStr: string): string {\n return kebabStr\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nexport function getSchemaRef(schemaName: string, mode: string): string {\n switch (mode) {\n case \"prisma\":\n case \"zod\":\n return `#/components/schemas/${schemaName}Schema`;\n case \"class-validator\":\n return `#/components/schemas/${schemaName}Dto`;\n default:\n return `#/components/schemas/${schemaName}`;\n }\n}\n\nexport async function generatePathsForModels(\n arkosConfig: ArkosConfig\n): Promise<OpenAPIV3.PathsObject> {\n const swaggerConfig = arkosConfig?.swagger;\n\n if (!swaggerConfig) return {};\n\n let paths: OpenAPIV3.PathsObject = {};\n const models = getModels();\n const mode = swaggerConfig!.mode;\n\n for (const model of models) {\n const modelName = kebabCase(model);\n const routeName = pluralize.plural(modelName);\n const pascalModelName = pascalCase(model);\n const humanReadableName = kebabToHuman(modelName);\n const humanReadableNamePlural = pluralize.plural(humanReadableName);\n\n // Import model modules to get router config\n const modelModules = await importPrismaModelModules(model, arkosConfig);\n const routerConfig = modelModules.router?.config;\n\n // Skip if router is completely disabled\n if (routerConfig?.disable === true) continue;\n\n // Generate main routes\n await generatePrismaModelMainRoutesPaths(\n paths,\n routeName,\n pascalModelName,\n humanReadableName,\n humanReadableNamePlural,\n routerConfig,\n mode\n );\n\n // Generate parent routes if configured\n if (routerConfig?.parent)\n await generatePrismaModelParentRoutePaths(\n paths,\n routeName,\n pascalModelName,\n humanReadableName,\n humanReadableNamePlural,\n routerConfig,\n mode\n );\n }\n\n // Add system routes\n paths = { ...paths, ...getSystemJsonSchemaPaths() };\n\n // Add authentication routes\n paths = { ...paths, ...getAuthenticationJsonSchemaPaths() };\n\n return paths;\n}\n"]}
|
package/dist/cjs/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.server=void 0,exports.terminateApplicationRunningProcessAndServer=terminateApplicationRunningProcessAndServer,exports.getArkosConfig=getArkosConfig,exports.getExpressApp=getExpressApp,exports.initApp=initApp;const app_1=require("./app"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper")),http_1=__importDefault(require("http")),
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.server=void 0,exports.terminateApplicationRunningProcessAndServer=terminateApplicationRunningProcessAndServer,exports.getArkosConfig=getArkosConfig,exports.getExpressApp=getExpressApp,exports.initApp=initApp;const app_1=require("./app"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper")),http_1=__importDefault(require("http")),models_helpers_1=require("./utils/helpers/models.helpers"),sheu_1=__importDefault(require("./utils/sheu"));process.on("uncaughtException",e=>{console.error(`
|
|
2
2
|
UNCAUGHT EXCEPTION! SHUTTING DOWN...
|
|
3
|
-
`),console.error(e.name,e.message),console.error(e),process.exit(1)
|
|
3
|
+
`),console.error(e.name,e.message),console.error(e),process.exit(1)});let server,_app,_arkosConfig={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:Number(process.env.CLI_PORT)||Number(process.env.PORT)||8e3,host:process.env.CLI_HOST||process.env.HOST||"localhost",fileUpload:{baseUploadDir:"uploads",baseRoute:"/api/uploads"},available:!1};async function initApp(e={}){(0,models_helpers_1.initializePrismaModels)(),_arkosConfig.available=!0,_arkosConfig=(0,deepmerge_helper_1.default)(_arkosConfig,e);const r=process.env.CLI_PORT||_arkosConfig.port||process.env.PORT||"port"in _arkosConfig?_arkosConfig.port:8e3;_app=await(0,app_1.bootstrap)(_arkosConfig);const t=new Date().toTimeString().split(" ")[0];return r?(exports.server=server=http_1.default.createServer(_app),_arkosConfig?.configureServer&&await _arkosConfig.configureServer(server),server.listen(Number(r),_arkosConfig.host,()=>{sheu_1.default.ready(`${sheu_1.default.gray(t)} server waiting on http://${_arkosConfig.host||"localhost"}:${r}`)})):sheu_1.default.warn(`${sheu_1.default.gray(t)} port set to undefined, hence no internal http server was setup.`),_app}process.on("unhandledRejection",e=>{console.error("UNHANDLED REJECTION! SHUTTING DOWN..."),console.error(e.name,e.message),console.error(e),server?.close(()=>{process.exit(1)})});function terminateApplicationRunningProcessAndServer(){server?.close(()=>{process.exit(1)})}function getArkosConfig(){return _arkosConfig}function getExpressApp(){return _app}
|
package/dist/cjs/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AAiGA,kGAIC;AAOD,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AAjHxB,+BAAkC;AAElC,wFAAyD;AACzD,gDAAwB;AACxB,
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AAiGA,kGAIC;AAOD,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AAjHxB,+BAAkC;AAElC,wFAAyD;AACzD,gDAAwB;AACxB,mEAAwE;AACxE,wDAAgC;AAEhC,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IAGtC,OAAO,CA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AC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\nimport { initializePrismaModels } from \"./utils/helpers/models.helpers\";\nimport sheu from \"./utils/sheu\";\n\nprocess.on(\"uncaughtException\", (err) => {\n // if (err.message.includes(\"EPIPE\")) return;\n\n console.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nlet _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n initializePrismaModels();\n _arkosConfig.available = true;\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port =\n process.env.CLI_PORT ||\n _arkosConfig.port ||\n process.env.PORT ||\n \"port\" in _arkosConfig\n ? _arkosConfig.port\n : 8000;\n\n _app = await bootstrap(_arkosConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (port) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(Number(port), _arkosConfig.host!, () => {\n sheu.ready(\n `${sheu.gray(time)} server waiting on http://${_arkosConfig.host || \"localhost\"}:${port}`\n );\n });\n } else {\n sheu.warn(\n `${sheu.gray(time)} port set to undefined, hence no internal http server was setup.`\n );\n }\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
|
|
@@ -27,7 +27,7 @@ async function devCommand(options = {}) {
|
|
|
27
27
|
const fileExt = (0, fs_helpers_1.getUserFileExtension)();
|
|
28
28
|
const entryPoint = path_1.default.resolve(process.cwd(), `src/app.${fileExt}`);
|
|
29
29
|
if (!fs_1.default.existsSync(entryPoint)) {
|
|
30
|
-
console.error(
|
|
30
|
+
console.error(`Could not find application entry point at ${entryPoint}`);
|
|
31
31
|
process.exit(1);
|
|
32
32
|
}
|
|
33
33
|
const getEnv = () => ({
|
|
@@ -68,23 +68,21 @@ async function devCommand(options = {}) {
|
|
|
68
68
|
}
|
|
69
69
|
else {
|
|
70
70
|
child = (0, child_process_1.spawn)("npx", [
|
|
71
|
-
"
|
|
72
|
-
"--
|
|
73
|
-
"
|
|
74
|
-
"--ext",
|
|
75
|
-
"js,json",
|
|
71
|
+
"node-dev",
|
|
72
|
+
"--respawn",
|
|
73
|
+
"--notify=false",
|
|
76
74
|
"--ignore",
|
|
77
|
-
"node_modules
|
|
75
|
+
"node_modules",
|
|
78
76
|
"--ignore",
|
|
79
|
-
"dist
|
|
77
|
+
"dist",
|
|
80
78
|
"--ignore",
|
|
81
|
-
"build
|
|
79
|
+
"build",
|
|
82
80
|
"--ignore",
|
|
83
|
-
".dist
|
|
81
|
+
".dist",
|
|
84
82
|
"--ignore",
|
|
85
|
-
".build
|
|
86
|
-
"--
|
|
87
|
-
"
|
|
83
|
+
".build",
|
|
84
|
+
"--watch",
|
|
85
|
+
"src",
|
|
88
86
|
entryPoint,
|
|
89
87
|
], {
|
|
90
88
|
stdio: "inherit",
|
|
@@ -143,6 +141,7 @@ async function devCommand(options = {}) {
|
|
|
143
141
|
"src",
|
|
144
142
|
"package.json",
|
|
145
143
|
"tsconfig.json",
|
|
144
|
+
"jsconfig.json",
|
|
146
145
|
"arkos.config.ts",
|
|
147
146
|
"arkos.config.js",
|
|
148
147
|
], {
|
|
@@ -157,7 +156,7 @@ async function devCommand(options = {}) {
|
|
|
157
156
|
/\.env.*/,
|
|
158
157
|
],
|
|
159
158
|
awaitWriteFinish: {
|
|
160
|
-
stabilityThreshold:
|
|
159
|
+
stabilityThreshold: 3000,
|
|
161
160
|
},
|
|
162
161
|
});
|
|
163
162
|
additionalWatcher.on("add", (filePath) => {
|
|
@@ -166,6 +165,9 @@ async function devCommand(options = {}) {
|
|
|
166
165
|
additionalWatcher.on("unlink", (filePath) => {
|
|
167
166
|
scheduleRestart(`${(0, fs_helpers_1.fullCleanCwd)(filePath)} has been deleted`);
|
|
168
167
|
});
|
|
168
|
+
additionalWatcher.on("change", (filePath) => {
|
|
169
|
+
console.log(`file changed`, filePath);
|
|
170
|
+
});
|
|
169
171
|
return additionalWatcher;
|
|
170
172
|
};
|
|
171
173
|
startServer();
|