arkos 1.3.0-canary.2 → 1.3.0-canary.3
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/README.md +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.controller.helpers.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +2 -2
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/app-error.js +1 -1
- package/dist/cjs/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +2 -2
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/cjs/modules/file-upload/file-upload.controller.js +1 -1
- package/dist/cjs/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/cjs/modules/file-upload/file-upload.service.js +1 -1
- package/dist/cjs/modules/file-upload/file-upload.service.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths.js +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes-paths.js +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes-paths.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
- package/dist/cjs/server.js +1 -1
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +7 -5
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/smart-fs-watcher.js +1 -0
- package/dist/cjs/utils/cli/utils/smart-fs-watcher.js.map +1 -0
- package/dist/cjs/utils/dynamic-loader.js +2 -2
- package/dist/cjs/utils/dynamic-loader.js.map +1 -1
- package/dist/cjs/utils/helpers/dynamic-loader.helpers.js +1 -1
- package/dist/cjs/utils/helpers/dynamic-loader.helpers.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +1 -1
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-schema-parser.js +4 -4
- package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/cjs/utils/sheu.js +1 -1
- package/dist/cjs/utils/sheu.js.map +1 -1
- package/dist/esm/modules/base/utils/helpers/base.controller.helpers.js.map +1 -1
- package/dist/esm/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +2 -2
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/app-error.js +1 -1
- package/dist/esm/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +2 -2
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/esm/modules/file-upload/file-upload.controller.js +1 -1
- package/dist/esm/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/esm/modules/file-upload/file-upload.service.js +1 -1
- package/dist/esm/modules/file-upload/file-upload.service.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +1 -1
- package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths.js +1 -1
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes-paths.js +1 -1
- package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes-paths.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js +1 -1
- 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 +7 -5
- package/dist/esm/utils/cli/dev.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/smart-fs-watcher.js +1 -0
- package/dist/esm/utils/cli/utils/smart-fs-watcher.js.map +1 -0
- package/dist/esm/utils/dynamic-loader.js +9 -9
- package/dist/esm/utils/dynamic-loader.js.map +1 -1
- package/dist/esm/utils/helpers/dynamic-loader.helpers.js +1 -1
- package/dist/esm/utils/helpers/dynamic-loader.helpers.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js +1 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-schema-parser.js +3 -3
- package/dist/esm/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/esm/utils/sheu.js +1 -1
- package/dist/esm/utils/sheu.js.map +1 -1
- package/dist/types/modules/error-handler/utils/error-handler.helpers.d.ts +17 -17
- package/dist/types/modules/file-upload/file-upload.controller.d.ts +0 -1
- package/dist/types/modules/file-upload/file-upload.service.d.ts +4 -5
- package/dist/types/modules/swagger/utils/helpers/swagger.router.helpers.d.ts +2 -0
- package/dist/types/utils/cli/utils/smart-fs-watcher.d.ts +11 -0
- package/dist/types/utils/dynamic-loader.d.ts +3 -16
- package/dist/types/utils/helpers/dynamic-loader.helpers.d.ts +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.controller.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.controller.helpers.ts"],"names":[],"mappings":";;;AAAA,+CAAmD;
|
|
1
|
+
{"version":3,"file":"base.controller.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.controller.helpers.ts"],"names":[],"mappings":";;;AAAA,+CAAmD;AAE5C,MAAM,YAAY,GAAG,GAAG,EAAE;IAC/B,MAAM,GAAG,GAAG,IAAA,sBAAa,GAAE,CAAC;IAC5B,MAAM,MAAM,GAAuC,EAAE,CAAC;IAEtD,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,UAAe,EAAE,EAAE;QAC5C,IAAI,UAAU,CAAC,KAAK,EAAE,CAAC;YAErB,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;gBACvD,MAAM,CAAC,IAAI,CAAC;oBACV,MAAM,EAAE,MAAM,CAAC,WAAW,EAAE;oBAC5B,IAAI,EAAE,UAAU,CAAC,KAAK,CAAC,IAAI;iBAC5B,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;aAAM,IAAI,UAAU,CAAC,MAAM,IAAI,UAAU,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YAExD,IAAI,QAAQ,GAAG,EAAE,CAAC;YAClB,IAAI,UAAU,CAAC,MAAM,EAAE,CAAC;gBAEtB,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;gBAG/C,IAAI,SAAS,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC;oBAElC,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;oBACjD,IAAI,KAAK,EAA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AAC,CAAC;gCAC9B,CAAC;qCAAM,CAAC;oCACN,QAAQ,GAAG,SAAS,CAAC;gCACvB,CAAC;4BACH,CAAC;wBACH,CAAC;6BAAM,CAAC;4BAEN,QAAQ,GAAG,QAAQ;gCACjB,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;oCAC3B,CAAC,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,GAAG,SAAS,CAAC;gCAC3D,CAAC,CAAC,SAAS,CAAC;wBAChB,CAAC;wBAGD,QAAQ,GAAG,QAAQ;6BAChB,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;6BACrB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;6BAClB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;wBAGtB,IAAI,QAAQ,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC;4BACjC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC;wBACvD,CAAC;wBAED,MAAM,CAAC,IAAI,CAAC;4BACV,MAAM,EAAE,MAAM,CAAC,WAAW,EAAE;4BAC5B,IAAI,EAAE,QAAQ;yBACf,CAAC,CAAC;oBACL,CAAC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AA1FW,QAAA,YAAY,gBA0FvB","sourcesContent":["import { getExpressApp } from \"../../../../server\";\n\nexport const getAppRoutes = () => {\n const app = getExpressApp();\n const routes: { method: string; path: string }[] = [];\n\n app._router.stack.forEach((middleware: any) => {\n if (middleware.route) {\n // Direct routes on the app\n Object.keys(middleware.route.methods).forEach((method) => {\n routes.push({\n method: method.toUpperCase(),\n path: middleware.route.path,\n });\n });\n } else if (middleware.handle && middleware.handle.stack) {\n // Extract the base path from the middleware's regexp pattern\n let basePath = \"\";\n if (middleware.regexp) {\n // Handle pattern like /^\\/api\\/?(?=\\/|$)/i\n const regexpStr = middleware.regexp.toString();\n\n // More robust pattern matching\n if (regexpStr.includes?.(\"/?(?=\")) {\n // Extract everything between the start and the '/?(?=' pattern\n const match = regexpStr.match(/\\/\\^(\\\\\\/[^?]+)/);\n if (match) {\n // Clean up the extracted path\n basePath = match[1].replace(/\\\\\\//g, \"/\");\n }\n } else {\n // Handle other regexp patterns\n const simpleMatch = regexpStr.match(/\\/\\^(\\\\\\/[^\\\\]+)/);\n if (simpleMatch) {\n basePath = simpleMatch[1].replace(/\\\\\\//g, \"/\");\n }\n }\n }\n\n // Process routes in the middleware's router\n middleware.handle.stack.forEach((routerMiddleware: any) => {\n if (routerMiddleware.route) {\n Object.keys(routerMiddleware.route.methods).forEach((method) => {\n let routePath = routerMiddleware.route.path;\n let fullPath;\n\n // Check if routePath already contains regex artifacts\n if (routePath.includes?.(\"/?(?=\")) {\n // Extract the actual path from the regex pattern\n const pathMatch = routePath.match(/\\/\\^?(\\\\\\/[^?]+|\\/[^?]+)/);\n if (pathMatch) {\n const cleanPath = pathMatch[1].replace(/\\\\\\//g, \"/\");\n fullPath = basePath ? basePath + cleanPath : cleanPath;\n } else {\n // If we can't clean it, at least extract what's after '/?(?='\n const fallbackMatch = routePath.match(/\\?\\(\\?=([^)]+)/);\n if (fallbackMatch) {\n fullPath = fallbackMatch[1];\n } else {\n fullPath = routePath; // Use as is if no pattern matches\n }\n }\n } else {\n // Normal path joining\n fullPath = basePath\n ? basePath.replace(/\\/$/, \"\") +\n (routePath.startsWith(\"/\") ? routePath : \"/\" + routePath)\n : routePath;\n }\n\n // Clean up any remaining regex artifacts\n fullPath = fullPath\n .replace(/\\\\\\//g, \"/\")\n .replace(/\\^/g, \"\")\n .replace(/\\$/g, \"\");\n\n // Remove any \"/?(?=\" patterns that might remain\n if (fullPath.includes?.(\"/?(?=\")) {\n fullPath = fullPath.replace(/\\/\\?\\(\\?=[^)]*\\)/g, \"\");\n }\n\n routes.push({\n method: method.toUpperCase(),\n path: fullPath,\n });\n });\n }\n });\n }\n });\n\n return routes;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.service.helpers.ts"],"names":[],"mappings":";;;;;AAUA,0CAoBC;AAoBD,wDAKC;AAED,wEAKC;AA8BD,gEAuLC;AAyBD,gDAgCC;AA3UD,yGAA+E;AAS/E,SAAgB,eAAe,CAAC,GAAwB;IACtD,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC;IAEhD,MAAM,MAAM,GAAwB,EAAE,CAAC;IAEvC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,IAAI,GAAG,KAAK,WAAW;YAAE,SAAS;QAElC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAC/B,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CACzE,CAAC;QACJ,CAAC;aAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACvD,MAAM,CAAC,GAAG,CAAC,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QACvC,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACtB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,gBAAgB,GAAG;I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AAY,EAAE,MAAM,GAAG,CAAC,EAAE,CAAC;QACpE,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5C,OAAO,YAAY,EAAE,IAAI,CAAC,CAAC,KAAkB,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IAC9E,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { RelationFields } from \"../../../../utils/dynamic-loader\";\nimport prismaSchemaParser from \"../../../../utils/prisma/prisma-schema-parser\";\nimport { PrismaField } from \"../../../../utils/prisma/types\";\n\n/**\n * Removes apiAction field from an object and all nested objects\n *\n * @param {Record<string, any>} obj - The object to clean\n * @returns {Record<string, any>} - The cleaned object\n */\nexport function removeApiAction(obj: Record<string, any>): Record<string, any> {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const result: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (key === \"apiAction\") continue;\n\n if (Array.isArray(value)) {\n result[key] = value.map((item) =>\n typeof item === \"object\" && item !== null ? removeApiAction(item) : item\n );\n } else if (typeof value === \"object\" && value !== null) {\n result[key] = removeApiAction(value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nconst prismaOperations = [\n \"create\",\n \"connect\",\n \"update\",\n \"delete\",\n \"disconnect\",\n \"deleteMany\",\n \"connectOrCreate\",\n \"upsert\",\n \"set\",\n];\n\n/**\n * Checks if an object is already formatted as a Prisma relation operation\n *\n * @param {Record<string, any>} obj - The object to check\n * @returns {boolean} - True if the object contains Prisma relation operations\n */\nexport function isPrismaRelationFormat(obj: Record<string, any>): boolean {\n if (!obj || typeof obj !== \"object\") return false;\n\n // Check if any key is a Prisma operation\n return prismaOperations.some((op) => op in obj);\n}\n\nexport function throwErrorIfApiActionIsInvalid(apiAction: string) {\n if (apiAction && !prismaOperations.includes(apiAction))\n throw Error(\n `Validation Error: Unknown value \"${apiAction}\" for apiAction field, available values are ${prismaOperations.join(\", \")}.`\n );\n}\n\n/**\n * Determines the appropriate Prisma operation (`create`, `connect`, `update`, `delete`, or `disconnect`)\n * for each relation field in the provided body based on its nested data and recursively does the same for each relation field.\n *\n * This function handles the following types of relations:\n * - **One-to-one**\n * - **One-to-many**\n *\n *\n * ### Operation Rules:\n *\n *\n * - **Create**: Used when the nested relation data is provided **without an `id` or unique field**.\n * - **Connect**: Used when the nested relation data contains **only an `id` or a unique field** (e.g., email).\n * - **Update**: Used when the nested relation data contains **both an `id` and additional fields**.\n * - **Delete**: Used when the nested relation data includes **`apiAction: \"delete\"`**.\n * - **Disconnect**: Used when the nested relation data includes **`apiAction: \"disconnect\"`**.\n *\n * The function will preserve existing Prisma operation formats if detected,\n * allowing developers to manually structure relation operations when needed.\n *\n * @param {Record<string, any>} body - The object containing relation fields to be processed.\n * @param {Object} relationFields - Defines relation field types.\n * @param {RelationFields[]} relationFields.singular - List of one-side relation field names (one-to-one).\n * @param {RelationFields[]} relationFields.list - List of many-side relation field names (one-to-many).\n * @param {string[]} ignoreActions - Optional list of apiAction values to ignore.\n * @returns {Record<string, any>} The transformed data with appropriate Prisma operations applied.\n */\nexport function handleRelationFieldsInBody(\n body: Record<string, any>,\n relationFields: ModelGroupRelationFields,\n ignoreActions: string[] = []\n) {\n let mutableBody = { ...body };\n\n relationFields?.list?.forEach((field) => {\n if (!body[field.name]) return;\n\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) {\n delete mutableBody[field.name];\n return;\n }\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) return;\n\n // Skip if the field is not an array (likely already handled manually)\n if (!Array.isArray(body[field.name])) return;\n\n const createData: any[] = [];\n const connectData: any[] = [];\n const updateData: any[] = [];\n const disconnectData: any[] = [];\n const deleteManyIds: any[] = [];\n\n body[field.name]?.forEach((bodyField: any) => {\n if (ignoreActions?.includes?.(bodyField?.apiAction)) return;\n\n const apiAction = bodyField?.apiAction;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n\n if (apiAction === \"delete\") {\n deleteManyIds.push(bodyField.id);\n } else if (apiAction === \"disconnect\") {\n disconnectData.push({ id: bodyField.id });\n } else if (canBeUsedToConnect(field.type, bodyField)) {\n // Handle connection with unique fields or ID\n const { apiAction, ...cleanedData } = bodyField;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n connectData.push(cleanedData);\n } else if (!bodyField?.id) {\n // If no ID, assume create operation\n let nestedRelations = getGroupedModelReations(field.type);\n\n let dataToPush = { ...bodyField };\n\n if (nestedRelations?.singular || nestedRelations?.list) {\n dataToPush = handleRelationFieldsInBody(\n dataToPush,\n nestedRelations,\n ignoreActions\n );\n }\n\n // Ensure apiAction is removed\n if (\"apiAction\" in dataToPush) {\n const { apiAction, ...rest } = dataToPush;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n dataToPush = rest;\n }\n\n createData.push(dataToPush);\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction, ...data } = bodyField;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n let nestedRelations = getGroupedModelReations(field.type);\n\n let dataToPush = data;\n if (nestedRelations?.singular || nestedRelations?.list) {\n dataToPush = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n updateData.push({\n where: { id },\n data: dataToPush,\n });\n }\n });\n\n mutableBody[field.name] = {\n ...(createData.length ? { create: createData } : {}),\n ...(connectData.length ? { connect: connectData } : {}),\n ...(updateData.length ? { update: updateData } : {}),\n ...(disconnectData.length ? { disconnect: disconnectData } : {}),\n ...(deleteManyIds.length\n ? { deleteMany: { id: { in: deleteManyIds } } }\n : {}),\n };\n });\n\n relationFields?.singular?.forEach((field) => {\n if (!body[field.name]) return;\n\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) {\n delete mutableBody[field.name];\n return;\n }\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n const relationData = body[field.name];\n let nestedRelations = getGroupedModelReations(field.type);\n\n if (relationData?.apiAction === \"delete\") {\n // Handle delete for singular relations\n mutableBody[field.name] = { delete: true };\n } else if (relationData?.apiAction === \"disconnect\") {\n // Handle disconnect for singular relations\n mutableBody[field.name] = { disconnect: true };\n } else if (canBeUsedToConnect(field.type, relationData)) {\n // Handle connection with unique fields or ID\n const { apiAction, ...cleanedData } = relationData;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n\n mutableBody[field.name] = { connect: cleanedData };\n } else if (!relationData?.id) {\n // If no ID, assume create operation\n let dataToCreate = { ...relationData };\n\n if (\"apiAction\" in dataToCreate) {\n const { apiAction, ...rest } = dataToCreate;\n throwErrorIfApiActionIsInvalid(apiAction);\n\n dataToCreate = rest;\n }\n\n if (nestedRelations?.singular || nestedRelations?.list) {\n dataToCreate = handleRelationFieldsInBody(\n dataToCreate,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = { create: dataToCreate };\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction, ...data } = relationData;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n\n let dataToUpdate = data;\n if (nestedRelations?.singular || nestedRelations?.list) {\n dataToUpdate = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = {\n update: {\n where: { id },\n data: dataToUpdate,\n },\n };\n }\n });\n\n // Remove any remaining apiAction fields from the top level\n if (\"apiAction\" in mutableBody) {\n throw Error(\n \"Validation Error: Invalid usage of apiAction field, it must only be used on relation fields whether single or multiple.\"\n );\n }\n\n // As a final step, recursively remove any remaining apiAction fields\n return removeApiAction(mutableBody);\n}\n\nexport type ModelGroupRelationFields = ReturnType<\n typeof getGroupedModelReations\n>;\n\nfunction getGroupedModelReations(modelName: string) {\n const relationsFields = prismaSchemaParser.getModelRelations(modelName);\n\n return {\n singular: relationsFields?.filter(\n (field) => field.isRelation && field.connectionField && !field.isArray\n ),\n list: relationsFields?.filter((field) => field.isRelation && field.isArray),\n };\n}\n\n/**\n * Checks if a field value can be used to connect to a model\n * This happens when the field contains only an ID or a single unique field\n *\n * @param {string} modelName - The model name to get unique fields for\n * @param {Record<string, any>} bodyField - The field value from the body\n * @returns {boolean} True if the field can be used for a connect operation\n */\nexport function canBeUsedToConnect(\n modelName: string,\n bodyField: Record<string, any> | undefined | null\n): boolean {\n // If the field is null or undefined, it can't be used to connect\n if (!bodyField) return false;\n\n // If the field has an apiAction that's not for connecting, return false\n if (bodyField.apiAction && ![\"connect\"]?.includes?.(bodyField.apiAction)) {\n return false;\n }\n\n // If explicitly marked for connect, allow it\n if (bodyField.apiAction === \"connect\") {\n return true;\n }\n\n // If only ID is present, it can be used to connect\n if (Object.keys(bodyField)?.length === 1 && bodyField?.id) {\n return true;\n }\n\n // Get unique fields for the model\n const uniqueFields = prismaSchemaParser.getModelUniqueFields(modelName) || [];\n\n // If the field has exactly one property and it's a unique field, it can be used to connect\n if (Object.keys(bodyField).length === 1 && uniqueFields?.length > 0) {\n const fieldName = Object.keys(bodyField)[0];\n return uniqueFields?.some((field: PrismaField) => field.name === fieldName);\n }\n\n return false;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.service.helpers.ts"],"names":[],"mappings":";;;;;AASA,0CAoBC;AAoBD,wDAKC;AAED,wEAKC;AA8BD,gEAuLC;AAyBD,gDAgCC;AA3UD,yGAA+E;AAS/E,SAAgB,eAAe,CAAC,GAAwB;IACtD,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC;IAEhD,MAAM,MAAM,GAAwB,EAAE,CAAC;IAEvC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,IAAI,GAAG,KAAK,WAAW;YAAE,SAAS;QAElC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,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S,CAAC,SAAS,IAAI,CAAC,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC;QACzE,OAAO,KAAK,CAAC;IACf,CAAC;IAGD,IAAI,SAAS,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAGD,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,KAAK,CAAC,IAAI,SAAS,EAAE,EAAE,EAAE,CAAC;QAC1D,OAAO,IAAI,CAAC;IACd,CAAC;IAGD,MAAM,YAAY,GAAG,8BAAkB,CAAC,oBAAoB,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;IAG9E,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,YAAY,EAAE,MAAM,GAAG,CAAC,EAAE,CAAC;QACpE,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5C,OAAO,YAAY,EAAE,IAAI,CAAC,CAAC,KAAkB,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IAC9E,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import prismaSchemaParser from \"../../../../utils/prisma/prisma-schema-parser\";\nimport { PrismaField } from \"../../../../utils/prisma/types\";\n\n/**\n * Removes apiAction field from an object and all nested objects\n *\n * @param {Record<string, any>} obj - The object to clean\n * @returns {Record<string, any>} - The cleaned object\n */\nexport function removeApiAction(obj: Record<string, any>): Record<string, any> {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const result: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (key === \"apiAction\") continue;\n\n if (Array.isArray(value)) {\n result[key] = value.map((item) =>\n typeof item === \"object\" && item !== null ? removeApiAction(item) : item\n );\n } else if (typeof value === \"object\" && value !== null) {\n result[key] = removeApiAction(value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nconst prismaOperations = [\n \"create\",\n \"connect\",\n \"update\",\n \"delete\",\n \"disconnect\",\n \"deleteMany\",\n \"connectOrCreate\",\n \"upsert\",\n \"set\",\n];\n\n/**\n * Checks if an object is already formatted as a Prisma relation operation\n *\n * @param {Record<string, any>} obj - The object to check\n * @returns {boolean} - True if the object contains Prisma relation operations\n */\nexport function isPrismaRelationFormat(obj: Record<string, any>): boolean {\n if (!obj || typeof obj !== \"object\") return false;\n\n // Check if any key is a Prisma operation\n return prismaOperations.some((op) => op in obj);\n}\n\nexport function throwErrorIfApiActionIsInvalid(apiAction: string) {\n if (apiAction && !prismaOperations.includes(apiAction))\n throw Error(\n `Validation Error: Unknown value \"${apiAction}\" for apiAction field, available values are ${prismaOperations.join(\", \")}.`\n );\n}\n\n/**\n * Determines the appropriate Prisma operation (`create`, `connect`, `update`, `delete`, or `disconnect`)\n * for each relation field in the provided body based on its nested data and recursively does the same for each relation field.\n *\n * This function handles the following types of relations:\n * - **One-to-one**\n * - **One-to-many**\n *\n *\n * ### Operation Rules:\n *\n *\n * - **Create**: Used when the nested relation data is provided **without an `id` or unique field**.\n * - **Connect**: Used when the nested relation data contains **only an `id` or a unique field** (e.g., email).\n * - **Update**: Used when the nested relation data contains **both an `id` and additional fields**.\n * - **Delete**: Used when the nested relation data includes **`apiAction: \"delete\"`**.\n * - **Disconnect**: Used when the nested relation data includes **`apiAction: \"disconnect\"`**.\n *\n * The function will preserve existing Prisma operation formats if detected,\n * allowing developers to manually structure relation operations when needed.\n *\n * @param {Record<string, any>} body - The object containing relation fields to be processed.\n * @param {Object} relationFields - Defines relation field types.\n * @param {RelationFields[]} relationFields.singular - List of one-side relation field names (one-to-one).\n * @param {RelationFields[]} relationFields.list - List of many-side relation field names (one-to-many).\n * @param {string[]} ignoreActions - Optional list of apiAction values to ignore.\n * @returns {Record<string, any>} The transformed data with appropriate Prisma operations applied.\n */\nexport function handleRelationFieldsInBody(\n body: Record<string, any>,\n relationFields: ModelGroupRelationFields,\n ignoreActions: string[] = []\n) {\n let mutableBody = { ...body };\n\n relationFields?.list?.forEach((field) => {\n if (!body[field.name]) return;\n\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) {\n delete mutableBody[field.name];\n return;\n }\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) return;\n\n // Skip if the field is not an array (likely already handled manually)\n if (!Array.isArray(body[field.name])) return;\n\n const createData: any[] = [];\n const connectData: any[] = [];\n const updateData: any[] = [];\n const disconnectData: any[] = [];\n const deleteManyIds: any[] = [];\n\n body[field.name]?.forEach((bodyField: any) => {\n if (ignoreActions?.includes?.(bodyField?.apiAction)) return;\n\n const apiAction = bodyField?.apiAction;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n\n if (apiAction === \"delete\") {\n deleteManyIds.push(bodyField.id);\n } else if (apiAction === \"disconnect\") {\n disconnectData.push({ id: bodyField.id });\n } else if (canBeUsedToConnect(field.type, bodyField)) {\n // Handle connection with unique fields or ID\n const { apiAction, ...cleanedData } = bodyField;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n connectData.push(cleanedData);\n } else if (!bodyField?.id) {\n // If no ID, assume create operation\n let nestedRelations = getGroupedModelReations(field.type);\n\n let dataToPush = { ...bodyField };\n\n if (nestedRelations?.singular || nestedRelations?.list) {\n dataToPush = handleRelationFieldsInBody(\n dataToPush,\n nestedRelations,\n ignoreActions\n );\n }\n\n // Ensure apiAction is removed\n if (\"apiAction\" in dataToPush) {\n const { apiAction, ...rest } = dataToPush;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n dataToPush = rest;\n }\n\n createData.push(dataToPush);\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction, ...data } = bodyField;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n let nestedRelations = getGroupedModelReations(field.type);\n\n let dataToPush = data;\n if (nestedRelations?.singular || nestedRelations?.list) {\n dataToPush = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n updateData.push({\n where: { id },\n data: dataToPush,\n });\n }\n });\n\n mutableBody[field.name] = {\n ...(createData.length ? { create: createData } : {}),\n ...(connectData.length ? { connect: connectData } : {}),\n ...(updateData.length ? { update: updateData } : {}),\n ...(disconnectData.length ? { disconnect: disconnectData } : {}),\n ...(deleteManyIds.length\n ? { deleteMany: { id: { in: deleteManyIds } } }\n : {}),\n };\n });\n\n relationFields?.singular?.forEach((field) => {\n if (!body[field.name]) return;\n\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) {\n delete mutableBody[field.name];\n return;\n }\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n const relationData = body[field.name];\n let nestedRelations = getGroupedModelReations(field.type);\n\n if (relationData?.apiAction === \"delete\") {\n // Handle delete for singular relations\n mutableBody[field.name] = { delete: true };\n } else if (relationData?.apiAction === \"disconnect\") {\n // Handle disconnect for singular relations\n mutableBody[field.name] = { disconnect: true };\n } else if (canBeUsedToConnect(field.type, relationData)) {\n // Handle connection with unique fields or ID\n const { apiAction, ...cleanedData } = relationData;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n\n mutableBody[field.name] = { connect: cleanedData };\n } else if (!relationData?.id) {\n // If no ID, assume create operation\n let dataToCreate = { ...relationData };\n\n if (\"apiAction\" in dataToCreate) {\n const { apiAction, ...rest } = dataToCreate;\n throwErrorIfApiActionIsInvalid(apiAction);\n\n dataToCreate = rest;\n }\n\n if (nestedRelations?.singular || nestedRelations?.list) {\n dataToCreate = handleRelationFieldsInBody(\n dataToCreate,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = { create: dataToCreate };\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction, ...data } = relationData;\n\n throwErrorIfApiActionIsInvalid(apiAction);\n\n let dataToUpdate = data;\n if (nestedRelations?.singular || nestedRelations?.list) {\n dataToUpdate = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = {\n update: {\n where: { id },\n data: dataToUpdate,\n },\n };\n }\n });\n\n // Remove any remaining apiAction fields from the top level\n if (\"apiAction\" in mutableBody) {\n throw Error(\n \"Validation Error: Invalid usage of apiAction field, it must only be used on relation fields whether single or multiple.\"\n );\n }\n\n // As a final step, recursively remove any remaining apiAction fields\n return removeApiAction(mutableBody);\n}\n\nexport type ModelGroupRelationFields = ReturnType<\n typeof getGroupedModelReations\n>;\n\nfunction getGroupedModelReations(modelName: string) {\n const relationsFields = prismaSchemaParser.getModelRelations(modelName);\n\n return {\n singular: relationsFields?.filter(\n (field) => field.isRelation && field.connectionField && !field.isArray\n ),\n list: relationsFields?.filter((field) => field.isRelation && field.isArray),\n };\n}\n\n/**\n * Checks if a field value can be used to connect to a model\n * This happens when the field contains only an ID or a single unique field\n *\n * @param {string} modelName - The model name to get unique fields for\n * @param {Record<string, any>} bodyField - The field value from the body\n * @returns {boolean} True if the field can be used for a connect operation\n */\nexport function canBeUsedToConnect(\n modelName: string,\n bodyField: Record<string, any> | undefined | null\n): boolean {\n // If the field is null or undefined, it can't be used to connect\n if (!bodyField) return false;\n\n // If the field has an apiAction that's not for connecting, return false\n if (bodyField.apiAction && ![\"connect\"]?.includes?.(bodyField.apiAction)) {\n return false;\n }\n\n // If explicitly marked for connect, allow it\n if (bodyField.apiAction === \"connect\") {\n return true;\n }\n\n // If only ID is present, it can be used to connect\n if (Object.keys(bodyField)?.length === 1 && bodyField?.id) {\n return true;\n }\n\n // Get unique fields for the model\n const uniqueFields = prismaSchemaParser.getModelUniqueFields(modelName) || [];\n\n // If the field has exactly one property and it's a unique field, it can be used to connect\n if (Object.keys(bodyField).length === 1 && uniqueFields?.length > 0) {\n const fieldName = Object.keys(bodyField)[0];\n return uniqueFields?.some((field: PrismaField) => field.name === fieldName);\n }\n\n return false;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,n,o,
|
|
1
|
+
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,n,o,a){a===void 0&&(a=o);var t=Object.getOwnPropertyDescriptor(n,o);(!t||("get"in t?!n.__esModule:t.writable||t.configurable))&&(t={enumerable:!0,get:function(){return n[o]}}),Object.defineProperty(e,a,t)}:function(e,n,o,a){a===void 0&&(a=o),e[a]=n[o]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),__importStar=this&&this.__importStar||function(){var e=function(n){return e=Object.getOwnPropertyNames||function(o){var a=[];for(var t in o)Object.prototype.hasOwnProperty.call(o,t)&&(a[a.length]=t);return a},e(n)};return function(n){if(n&&n.__esModule)return n;var o={};if(n!=null)for(var a=e(n),t=0;t<a.length;t++)a[t]!=="default"&&__createBinding(o,n,a[t]);return __setModuleDefault(o,n),o}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=errorHandler;const app_error_1=__importDefault(require("./utils/app-error")),errorControllerHelper=__importStar(require("./utils/error-handler.helpers")),server_1=require("../../server");function errorHandler(e,n,o,a){if(console.error("[\x1B[31mError\x1B[0m]:",e),e.statusCode=e.statusCode||500,e.status=e.status||"error",process.env.NODE_ENV!=="production")return sendDevelopmentError(e,n,o);let t={...e,message:e.message};e.name==="JsonWebTokenError"&&(t=errorControllerHelper.handleJWTError()),e.name==="TokenExpiredError"&&(t=errorControllerHelper.handleJWTExpired()),e.name==="PrismaClientValidationError"&&(t=errorControllerHelper.handlePrismaClientValidationError(e)),e.name==="PrismaClientInitializationError"&&(t=errorControllerHelper.handlePrismaClientInitializationError(e)),e.code==="P1000"&&(t=errorControllerHelper.handleAuthenticationError(e)),e.code==="P1001"&&(t=errorControllerHelper.handleServerNotReachableError(e)),e.code==="P1002"&&(t=errorControllerHelper.handleConnectionTimeoutError(e)),e.code==="P1003"&&(t=errorControllerHelper.handleDatabaseNotFoundError(e)),e.code==="P2000"&&(t=errorControllerHelper.handleFieldValueTooLargeError(e)),e.code==="P2001"&&(t=errorControllerHelper.handleRecordNotFoundError(e)),e.code==="P2002"&&(t=errorControllerHelper.handleUniqueConstraintError(e)),e.code==="P2003"&&(t=errorControllerHelper.handleForeignKeyConstraintError(e)),e.code==="P2004"&&(t=errorControllerHelper.handleConstraintFailedError(e)),e.code==="P2025"&&(t=errorControllerHelper.handleNonExistingRecord(e)),e.code==="P3000"&&(t=errorControllerHelper.handleSchemaCreationFailedError(e)),e.code==="P3001"&&(t=errorControllerHelper.handleMigrationAlreadyAppliedError(e)),e.code==="P3002"&&(t=errorControllerHelper.handleMigrationScriptFailedError(e)),e.code==="P3003"&&(t=errorControllerHelper.handleVersionMismatchError(e)),e.name==="NetworkError"&&(t=errorControllerHelper.handleNetworkError(e)),t.isOperational||(t=new app_error_1.default("Internal server error",500)),sendProductionError(t,n,o)}function sendDevelopmentError(e,n,o){n.originalUrl.startsWith("/api")?o.status(e.statusCode).json({...e,message:e.message.split(`
|
|
2
2
|
`)[e.message.split(`
|
|
3
3
|
`).length-1],stack:e.stack?.split(`
|
|
4
|
-
`)}):o.status(e.statusCode).json({title:"
|
|
4
|
+
`)}):o.status(e.statusCode).json({title:"Internal server error",message:e.message})}function sendProductionError(e,n,o){if(n.originalUrl.startsWith("/api")){e.isOperational?o.status(e.statusCode).json({status:e.status,message:e.message,meta:e.meta||{},code:e.code||"unknown"}):o.status(500).json({status:"error",message:"Internal server error"});return}if(e.isOperational){o.status(e.statusCode).json({title:"Internal server error",message:e.message});return}o.status(e.statusCode).json({title:"Internal server error",message:"Please try again later."})}process.on("SIGTERM",()=>{process.env.NODE_ENV!=="production"&&process.env.NODE_ENV!=="staging"?process.exit():(console.error("SIGTERM RECEIVED in Production. Shutting down gracefully!"),server_1.server.close(()=>{console.error("Process terminated!!!"),process.exit()}))});
|
|
@@ -1 +1 @@
|
|
|
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,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;IAGnC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACvC,OAAO,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;IAG7C,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;IACvE,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAiC;QAChD,KAAK,GAAG,qBAAqB,CAAC,qCAAqC,CAAC,GAAG,CAAC,CAAC;IAG3E,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO;QACtB,KAAK,GAAG,qBAAqB,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC;IAC/D,IAAI,GAAG,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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 // 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 return sendDevelopmentError(err, req, res);\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 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 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,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;IAGnC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACvC,OAAO,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;IA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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} _ - 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 // 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 return sendDevelopmentError(err, req, res);\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 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 if (!error.isOperational) error = new AppError(\"Internal server error\", 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: \"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 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class AppError extends Error{constructor(t,
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class AppError extends Error{constructor(r,t,s,e){super(r),this.message=r||"An error occurred, try again!",this.statusCode=t,this.status=`${t}`.startsWith("4")?"fail":"error",this.isOperational=!0,this.code=e||"Unknown",this.meta=s,this.missing=!1,Error.captureStackTrace(this,this.constructor)}}exports.default=AppError;
|
|
@@ -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,IAA0B,EAC1B,IAAa;QAEb,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,OAAO,GAAG,OAAO,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,IAA0B,EAC1B,IAAa;QAEb,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,+BAA+B,CAAC;QAC1D,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,GAAG,UAAU,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;QACjE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,SAAS,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QAErB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAClD,CAAC;CACF;AAED,kBAAe,QAAQ,CAAC","sourcesContent":["/**\n * Custom error class for handling application errors.\n *\n * @extends {Error}\n *\n * @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, { field: 'id' }, 'USER_ID_MISSING');\n * }\n * // Simulate a user not found scenario\n * throw new AppError('User not found', 404, { userId: id }, 'USER_NOT_FOUND');\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;\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 meta?: Record<string, any>,\n code?: 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 this.code = code || \"Unknown\";\n this.meta = meta;\n this.missing = false;\n\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\nexport default AppError;\n"]}
|
|
@@ -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.handleJWTError=handleJWTError,exports.handleJWTExpired=handleJWTExpired,exports.handlePrismaClientValidationError=handlePrismaClientValidationError,exports.handleAuthenticationError=handleAuthenticationError,exports.handleServerNotReachableError=handleServerNotReachableError,exports.handleConnectionTimeoutError=handleConnectionTimeoutError,exports.handleDatabaseNotFoundError=handleDatabaseNotFoundError,exports.handleEnvironmentVariableError=handleEnvironmentVariableError,exports.handleFieldValueTooLargeError=handleFieldValueTooLargeError,exports.handleRecordNotFoundError=handleRecordNotFoundError,exports.handleUniqueConstraintError=handleUniqueConstraintError,exports.handleForeignKeyConstraintError=handleForeignKeyConstraintError,exports.handleConstraintFailedError=handleConstraintFailedError,exports.handleInvalidFieldValueError=handleInvalidFieldValueError,exports.handleInvalidFieldProvidedError=handleInvalidFieldProvidedError,exports.handleDataValidationError=handleDataValidationError,exports.handleQueryParsingError=handleQueryParsingError,exports.handleInvalidQueryFormatError=handleInvalidQueryFormatError,exports.handleRawQueryExecutionError=handleRawQueryExecutionError,exports.handleNullConstraintViolationError=handleNullConstraintViolationError,exports.handleSchemaCreationFailedError=handleSchemaCreationFailedError,exports.handleMigrationAlreadyAppliedError=handleMigrationAlreadyAppliedError,exports.handleMigrationScriptFailedError=handleMigrationScriptFailedError,exports.handleVersionMismatchError=handleVersionMismatchError,exports.handleMigrationFileReadError=handleMigrationFileReadError,exports.handleSchemaDriftError=handleSchemaDriftError,exports.handleSchemaSyntaxError=handleSchemaSyntaxError,exports.handleClientTypeError=handleClientTypeError,exports.handleDynamicQueryError=handleDynamicQueryError,exports.handleRelationLoadingError=handleRelationLoadingError,exports.handleBinaryError=handleBinaryError,exports.handleNetworkError=handleNetworkError,exports.handleUnhandledPromiseError=handleUnhandledPromiseError,exports.handleDataTypeError=handleDataTypeError,exports.handleEmptyResultError=handleEmptyResultError,exports.handleNonExistingRecord=handleNonExistingRecord,exports.handlePrismaClientInitializationError=handlePrismaClientInitializationError;const app_error_1=__importDefault(require("./app-error"));function handleJWTError(){return new app_error_1.default("Invalid token. Please log in again!",401)}function handleJWTExpired(){return new app_error_1.default("Your token has expired, Please log again!",401)}function handlePrismaClientValidationError(e){const r=e?.message
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleJWTError=handleJWTError,exports.handleJWTExpired=handleJWTExpired,exports.handlePrismaClientValidationError=handlePrismaClientValidationError,exports.handleAuthenticationError=handleAuthenticationError,exports.handleServerNotReachableError=handleServerNotReachableError,exports.handleConnectionTimeoutError=handleConnectionTimeoutError,exports.handleDatabaseNotFoundError=handleDatabaseNotFoundError,exports.handleEnvironmentVariableError=handleEnvironmentVariableError,exports.handleFieldValueTooLargeError=handleFieldValueTooLargeError,exports.handleRecordNotFoundError=handleRecordNotFoundError,exports.handleUniqueConstraintError=handleUniqueConstraintError,exports.handleForeignKeyConstraintError=handleForeignKeyConstraintError,exports.handleConstraintFailedError=handleConstraintFailedError,exports.handleInvalidFieldValueError=handleInvalidFieldValueError,exports.handleInvalidFieldProvidedError=handleInvalidFieldProvidedError,exports.handleDataValidationError=handleDataValidationError,exports.handleQueryParsingError=handleQueryParsingError,exports.handleInvalidQueryFormatError=handleInvalidQueryFormatError,exports.handleRawQueryExecutionError=handleRawQueryExecutionError,exports.handleNullConstraintViolationError=handleNullConstraintViolationError,exports.handleSchemaCreationFailedError=handleSchemaCreationFailedError,exports.handleMigrationAlreadyAppliedError=handleMigrationAlreadyAppliedError,exports.handleMigrationScriptFailedError=handleMigrationScriptFailedError,exports.handleVersionMismatchError=handleVersionMismatchError,exports.handleMigrationFileReadError=handleMigrationFileReadError,exports.handleSchemaDriftError=handleSchemaDriftError,exports.handleSchemaSyntaxError=handleSchemaSyntaxError,exports.handleClientTypeError=handleClientTypeError,exports.handleDynamicQueryError=handleDynamicQueryError,exports.handleRelationLoadingError=handleRelationLoadingError,exports.handleBinaryError=handleBinaryError,exports.handleNetworkError=handleNetworkError,exports.handleUnhandledPromiseError=handleUnhandledPromiseError,exports.handleDataTypeError=handleDataTypeError,exports.handleEmptyResultError=handleEmptyResultError,exports.handleNonExistingRecord=handleNonExistingRecord,exports.handlePrismaClientInitializationError=handlePrismaClientInitializationError;const app_error_1=__importDefault(require("./app-error"));function handleJWTError(){return new app_error_1.default("Invalid token. Please log in again!",401)}function handleJWTExpired(){return new app_error_1.default("Your token has expired, Please log again!",401)}function handlePrismaClientValidationError(e){const r=e?.message?.split(`
|
|
2
2
|
`)[e?.message.split(`
|
|
3
|
-
`).length-1];return new app_error_1.default(r,400)}function handleAuthenticationError(e){const r="Authentication failed against the database server. Please check your credentials.";return new app_error_1.default(r,401)}function handleServerNotReachableError(e){const r="The database server is not reachable. Verify your connection string or ensure the server is online.";return new app_error_1.default(r,503)}function handleConnectionTimeoutError(e){const r="Connection to the database timed out. Please check server performance or network connectivity.";return new app_error_1.default(r,504)}function handleDatabaseNotFoundError(e){const r="The specified database does not exist on the server.";return new app_error_1.default(r,404)}function handleEnvironmentVariableError(e){const n=`Missing or invalid environment variables: ${e?.missing||"unknown environment variables"}. Please check your configuration.`;return new app_error_1.default(n,500)}function handleFieldValueTooLargeError(e){const r=`The value for the field "${e?.meta?.field_name}" is too large. Please provide a smaller value.`;return new app_error_1.default(r,400)}function handleRecordNotFoundError(e){const r="No record found for the given query. Ensure the query parameters are correct.";return new app_error_1.default(r,404)}function handleUniqueConstraintError(e){const n=`Duplicate value detected for the unique field(s): ${e?.meta?.target||"unknown field"}. Please use a different value.`;return new app_error_1.default(n,409)}function handleForeignKeyConstraintError(e){const r="Foreign key constraint violation. Ensure that the referenced record exists.";return new app_error_1.default(r,400)}function handleConstraintFailedError(e){const n=`A database constraint "${e?.meta?.constraint||"unknown constraint"}" failed. Please review your input data.`;return new app_error_1.default(n,400)}function handleInvalidFieldValueError(e){const n=`Invalid value provided for the field "${e?.meta?.field_name||"unknown field"}". Please provide a valid value.`;return new app_error_1.default(n,400)}function handleInvalidFieldProvidedError(e){const n=`The field "${e?.meta?.field_name||"unknown field"}" has been provided with an invalid value. Check the data and try again.`;return new app_error_1.default(n,400)}function handleDataValidationError(e){const r="Data validation error occurred. Please ensure all fields meet the required criteria.";return new app_error_1.default(r,400)}function handleQueryParsingError(e){const n=`Failed to parse the query: "${e?.meta?.query||"unknown query"}". Check the syntax and structure.`;return new app_error_1.default(n,400)}function handleInvalidQueryFormatError(e){const n=`The query format is invalid: "${e?.meta?.query||"unknown query"}". Ensure the query adheres to the expected format.`;return new app_error_1.default(n,400)}function handleRawQueryExecutionError(e){const r="An error occurred during the execution of a raw query. Verify the query and try again.";return new app_error_1.default(r,500)}function handleNullConstraintViolationError(e){const n=`The field "${e?.meta?.field_name||"unknown field"}" cannot be null. Please provide a value.`;return new app_error_1.default(n,400)}function handleSchemaCreationFailedError(e){const r="Failed to create the database schema. Verify the schema definition and try again.";return new app_error_1.default(r,500)}function handleMigrationAlreadyAppliedError(e){const n=`The migration "${e?.meta?.migration||"unknown migration"}" has already been applied to the database.`;return new app_error_1.default(n,409)}function handleMigrationScriptFailedError(e){const n=`The migration script "${e?.meta?.migration||"unknown migration"}" failed. Review the script and resolve any issues.`;return new app_error_1.default(n,500)}function handleVersionMismatchError(e){const r="Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.";return new app_error_1.default(r,400)}function handleMigrationFileReadError(e){const n=`Failed to read the migration file "${e?.meta?.migration_file||"unknown file"}". Ensure the file exists and is accessible.`;return new app_error_1.default(n,500)}function handleSchemaDriftError(e){const r="Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.";return new app_error_1.default(r,400)}function handleSchemaSyntaxError(e){const r="Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.";return new app_error_1.default(r,500)}function handleClientTypeError(e){const r="Type error, Ensure proper usage of methods and correct data types.";return new app_error_1.default(r,400)}function handleDynamicQueryError(e){const r="Error constructing or executing a dynamic query. Verify query structure and parameters.";return new app_error_1.default(r,400)}function handleRelationLoadingError(e){const n=`Error loading relation "${e?.meta?.relation||"unknown relation"}". Ensure it is correctly defined and included in the query.`;return new app_error_1.default(n,400)}function handleBinaryError(e){const n=`Error with Prisma binary "${e?.meta?.binary||"unknown binary"}". Ensure the binary is properly installed and compatible.`;return new app_error_1.default(n,500)}function handleNetworkError(e){const r="Network error: Unable to connect to the database or internet. Please check your network connection.";return new app_error_1.default(r,500)}function handleUnhandledPromiseError(e){const r="Unhandled promise rejection detected. Please check asynchronous code for proper error handling.";return new app_error_1.default(r,500)}function handleDataTypeError(e){const r=e?.meta?.field||"unknown field",n=e?.meta?.expected_type||"unknown type",
|
|
3
|
+
`).length-1];return new app_error_1.default(r,400)}function handleAuthenticationError(e){const r="Authentication failed against the database server. Please check your credentials.";return new app_error_1.default(r,401)}function handleServerNotReachableError(e){const r="The database server is not reachable. Verify your connection string or ensure the server is online.";return new app_error_1.default(r,503)}function handleConnectionTimeoutError(e){const r="Connection to the database timed out. Please check server performance or network connectivity.";return new app_error_1.default(r,504)}function handleDatabaseNotFoundError(e){const r="The specified database does not exist on the server.";return new app_error_1.default(r,404)}function handleEnvironmentVariableError(e){const n=`Missing or invalid environment variables: ${e?.missing||"unknown environment variables"}. Please check your configuration.`;return new app_error_1.default(n,500)}function handleFieldValueTooLargeError(e){const r=`The value for the field "${e?.meta?.field_name}" is too large. Please provide a smaller value.`;return new app_error_1.default(r,400)}function handleRecordNotFoundError(e){const r="No record found for the given query. Ensure the query parameters are correct.";return new app_error_1.default(r,404)}function handleUniqueConstraintError(e){const n=`Duplicate value detected for the unique field(s): ${e?.meta?.target||"unknown field"}. Please use a different value.`;return new app_error_1.default(n,409)}function handleForeignKeyConstraintError(e){const r="Foreign key constraint violation. Ensure that the referenced record exists.";return new app_error_1.default(r,400)}function handleConstraintFailedError(e){const n=`A database constraint "${e?.meta?.constraint||"unknown constraint"}" failed. Please review your input data.`;return new app_error_1.default(n,400)}function handleInvalidFieldValueError(e){const n=`Invalid value provided for the field "${e?.meta?.field_name||"unknown field"}". Please provide a valid value.`;return new app_error_1.default(n,400)}function handleInvalidFieldProvidedError(e){const n=`The field "${e?.meta?.field_name||"unknown field"}" has been provided with an invalid value. Check the data and try again.`;return new app_error_1.default(n,400)}function handleDataValidationError(e){const r="Data validation error occurred. Please ensure all fields meet the required criteria.";return new app_error_1.default(r,400)}function handleQueryParsingError(e){const n=`Failed to parse the query: "${e?.meta?.query||"unknown query"}". Check the syntax and structure.`;return new app_error_1.default(n,400)}function handleInvalidQueryFormatError(e){const n=`The query format is invalid: "${e?.meta?.query||"unknown query"}". Ensure the query adheres to the expected format.`;return new app_error_1.default(n,400)}function handleRawQueryExecutionError(e){const r="An error occurred during the execution of a raw query. Verify the query and try again.";return new app_error_1.default(r,500)}function handleNullConstraintViolationError(e){const n=`The field "${e?.meta?.field_name||"unknown field"}" cannot be null. Please provide a value.`;return new app_error_1.default(n,400)}function handleSchemaCreationFailedError(e){const r="Failed to create the database schema. Verify the schema definition and try again.";return new app_error_1.default(r,500)}function handleMigrationAlreadyAppliedError(e){const n=`The migration "${e?.meta?.migration||"unknown migration"}" has already been applied to the database.`;return new app_error_1.default(n,409)}function handleMigrationScriptFailedError(e){const n=`The migration script "${e?.meta?.migration||"unknown migration"}" failed. Review the script and resolve any issues.`;return new app_error_1.default(n,500)}function handleVersionMismatchError(e){const r="Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.";return new app_error_1.default(r,400)}function handleMigrationFileReadError(e){const n=`Failed to read the migration file "${e?.meta?.migration_file||"unknown file"}". Ensure the file exists and is accessible.`;return new app_error_1.default(n,500)}function handleSchemaDriftError(e){const r="Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.";return new app_error_1.default(r,400)}function handleSchemaSyntaxError(e){const r="Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.";return new app_error_1.default(r,500)}function handleClientTypeError(e){const r="Type error, Ensure proper usage of methods and correct data types.";return new app_error_1.default(r,400)}function handleDynamicQueryError(e){const r="Error constructing or executing a dynamic query. Verify query structure and parameters.";return new app_error_1.default(r,400)}function handleRelationLoadingError(e){const n=`Error loading relation "${e?.meta?.relation||"unknown relation"}". Ensure it is correctly defined and included in the query.`;return new app_error_1.default(n,400)}function handleBinaryError(e){const n=`Error with Prisma binary "${e?.meta?.binary||"unknown binary"}". Ensure the binary is properly installed and compatible.`;return new app_error_1.default(n,500)}function handleNetworkError(e){const r="Network error: Unable to connect to the database or internet. Please check your network connection.";return new app_error_1.default(r,500)}function handleUnhandledPromiseError(e){const r="Unhandled promise rejection detected. Please check asynchronous code for proper error handling.";return new app_error_1.default(r,500)}function handleDataTypeError(e){const r=e?.meta?.field||"unknown field",n=e?.meta?.expected_type||"unknown type",t=`Invalid data type for field "${r}". Expected type: ${n}.`;return new app_error_1.default(t,400)}function handleEmptyResultError(e){const r="Empty result: No data was found for the given query. Ensure the query criteria are correct.";return new app_error_1.default(r,404)}function handleNonExistingRecord(e){const r=e?.meta?.cause||"Operation could not be completed as the required record was not found";return new app_error_1.default(r,404,e.meta||{},"RecordNotFound")}function handlePrismaClientInitializationError(e){return new app_error_1.default("Service temporarily unavailable",503,{},"DatabaseNotAvailable")}
|
|
@@ -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,sDAG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mB,CAAC,GAAa;IAC/C,MAAM,KAAK,GAAG,GAAG,EAAE,IAAI,EAAE,KAAK,IAAI,eAAe,CAAC;IAClD,MAAM,YAAY,GAAG,GAAG,EAAE,IAAI,EAAE,aAAa,IAAI,cAAc,CAAC;IAChE,MAAM,OAAO,GAAG,gCAAgC,KAAK,qBAAqB,YAAY,GAAG,CAAC;IAC1F,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,sBAAsB,CAAC,GAAa;IAClD,MAAM,OAAO,GAAG,6FAA6F,CAAC;IAC9G,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,sBAAsB,CAAC,CAAC;AAC5E,CAAC;AAED,SAAgB,qCAAqC,CAAC,CAAM;IAC1D,OAAO,IAAI,mBAAQ,CACjB,4BAA4B,EAC5B,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 = 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\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Database is not available.\",\n 503,\n {},\n \"DatabaseNotAvailable\"\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/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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 +1 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(m){return m&&m.__esModule?m:{default:m}};Object.defineProperty(exports,"__esModule",{value:!0});const app_error_1=__importDefault(require("../error-handler/utils/app-error")),file_upload_service_1=require("./file-upload.service"),path_1=__importDefault(require("path")),fs_1=__importDefault(require("fs")),catch_async_1=__importDefault(require("../error-handler/utils/catch-async")),server_1=require("../../server"),file_upload_helpers_1=require("./utils/helpers/file-upload.helpers"),dynamic_loader_1=require("../../utils/dynamic-loader");class FileUploadController{constructor(){this.uploadFile=(0,catch_async_1.default)(async(e,u,t)=>{this.interceptors=(0,dynamic_loader_1.getModuleComponents)("file-upload")?.interceptors||{};const{fileType:s}=e.params,{format:a,width:g,height:y,resizeTo:U}=e.query,f={format:a,width:g,height:y,resizeTo:U},{documentUploadService:o,fileUploadService:n,imageUploadService:w,videoUploadService:v}=(0,file_upload_service_1.getFileUploadServices)(),{fileUpload:F}=(0,server_1.getArkosConfig)(),h=F?.baseUploadDir||"/uploads",_=path_1.default.resolve(process.cwd(),h,s);try{await fs_1.default.promises.access(_)}catch{await fs_1.default.promises.mkdir(_,{recursive:!0})}let p;switch(s){case"images":p=w;break;case"videos":p=v;break;case"documents":p=o;break;case"files":p=n;break;default:return t(new app_error_1.default("Invalid file type",400))}p.handleMultipleUpload()(e,u,async r=>{if(r)return t(r);let l;if(e.files&&Array.isArray(e.files)&&e.files.length>0)s==="images"?l=await Promise.all(e.files.map(d=>(0,file_upload_helpers_1.processImage)(e,d.path,f))):l=await Promise.all(e.files.map(d=>(0,file_upload_helpers_1.processFile)(e,d.path))),l=l.filter(d=>d!==null);else if(e.file)s==="images"?l=await(0,file_upload_helpers_1.processImage)(e,e.file.path,f):l=await(0,file_upload_helpers_1.processFile)(e,e.file.path);else return t(new app_error_1.default("No file uploaded",400));const i={success:!0,data:l,message:Array.isArray(l)?`${l.length} files uploaded successfully`:"File uploaded successfully"};if(this.interceptors?.afterUploadFile)return e.responseData=i,e.responseStatus=200,t();u.status(200).json(i)})}),this.deleteFile=(0,catch_async_1.default)(async(e,u,t)=>{this.interceptors=(0,dynamic_loader_1.getModuleComponents)("file-upload")?.interceptors||{};const{fileType:s,fileName:a}=e.params,{documentUploadService:g,fileUploadService:y,imageUploadService:U,videoUploadService:f}=(0,file_upload_service_1.getFileUploadServices)();let o;switch(s){case"images":o=U;break;case"videos":o=f;break;case"documents":o=g;break;case"files":o=y;break;default:return t(new app_error_1.default("Invalid file type",400))}try{const{fileUpload:n}=(0,server_1.getArkosConfig)(),w=n?.baseRoute||"/api/uploads";if(new RegExp(`${w}/${s}/${a}`).test(e.originalUrl)){const h=`${e.protocol}://${e.get("host")}${e.originalUrl}`;await o.deleteFileByUrl(h)}else await o.deleteFileByName(a,s);if(this.interceptors.afterDeleteFile)return e.responseStatus=204,t();u.status(204).json()}catch(n){return n instanceof app_error_1.default?t(n):t(new app_error_1.default("File not found",404))}}),this.updateFile=(0,catch_async_1.default)(async(e,u,t)=>{this.interceptors=(0,dynamic_loader_1.getModuleComponents)("file-upload")?.interceptors||{};const{fileType:s,fileName:a}=e.params,{format:g,width:y,height:U,resizeTo:f}=e.query,o={format:g,width:y,height:U,resizeTo:f},{documentUploadService:n,fileUploadService:w,imageUploadService:v,videoUploadService:F}=(0,file_upload_service_1.getFileUploadServices)(),{fileUpload:h}=(0,server_1.getArkosConfig)(),_=h?.baseUploadDir||"/uploads",p=path_1.default.resolve(process.cwd(),_,s);try{await fs_1.default.promises.access(p)}catch{await fs_1.default.promises.mkdir(p,{recursive:!0})}let r;switch(s){case"images":r=v;break;case"videos":r=F;break;case"documents":r=n;break;case"files":r=w;break;default:return t(new app_error_1.default("Invalid file type",400))}r.handleMultipleUpload()(e,u,async l=>{if(l)return t(l);if(!e.file&&(!e.files||!Array.isArray(e.files)||e.files.length===0))return t(new app_error_1.default("No new file uploaded",400));if(a&&a.trim()!=="")try{const c=h?.baseRoute||"/api/uploads";if(new RegExp(`${c}/${s}/${a}`).test(e.originalUrl)){const b=`${e.protocol}://${e.get("host")}${e.originalUrl}`;await r.deleteFileByUrl(b)}else await r.deleteFileByName(a,s)}catch(c){console.warn(`Could not delete old file: ${a}`,c)}let i;e.files&&Array.isArray(e.files)&&e.files.length>0?(s==="images"?i=await Promise.all(e.files.map(c=>(0,file_upload_helpers_1.processImage)(e,c.path,o))):i=await Promise.all(e.files.map(c=>(0,file_upload_helpers_1.processFile)(e,c.path))),i=i.filter(c=>c!==null)):e.file&&(s==="images"?i=await(0,file_upload_helpers_1.processImage)(e,e.file.path,o):i=await(0,file_upload_helpers_1.processFile)(e,e.file.path));const d={success:!0,data:i,message:Array.isArray(i)?a&&a.trim()!==""?`File updated successfully. ${i.length} new files uploaded`:`${i.length} files uploaded successfully`:a&&a.trim()!==""?"File updated successfully":"File uploaded successfully"};if(this.interceptors.afterUpdateFile)return e.responseData=d,e.responseStatus=200,t();u.status(200).json(d)})})}}const fileUploadController=new FileUploadController;exports.default=fileUploadController;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,+DAAiE;AAKjE,MAAM,oBAAoB;IAA1B;QAeE,eAAU,GAAG,IA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C,CAAC;oBACzD,OAAO;gBACT,CAAC;gBAED,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE;oBACjB,eAAe,EAAE,SAAS,KAAK,IAAI,GAAG,IAAI,QAAQ,EAAE;oBACpD,eAAe,EAAE,OAAO;oBACxB,gBAAgB,EAAE,GAAG,GAAG,KAAK,GAAG,CAAC;oBACjC,cAAc,EAAE,0BAA0B;oBAC1C,qBAAqB,EAAE,qBAAqB,QAAQ,GAAG;iBACxD,CAAC,CAAC;gBAEH,YAAE,CAAC,gBAAgB,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1D,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE;oBACjB,gBAAgB,EAAE,QAAQ;oBAC1B,cAAc,EAAE,0BAA0B;oBAC1C,qBAAqB,EAAE,qBAAqB,QAAQ,GAAG;iBACxD,CAAC,CAAC;gBACH,YAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1C,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;CAAA;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nclass FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Ensure upload directory exists\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n // Create directory if it doesn't exist\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n // Select the appropriate uploader service based on file type\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n // Handle the file upload\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n // Process all uploaded files\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n // Process multiple image files with image transformations\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n // Just store other file types without processing\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n if (fileType === \"images\") {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(new AppError(\"No file uploaded\", 400));\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n req.responseData = jsonContent;\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // This checks if the URL follows the expected format: /api/files/{fileType}/{fileName}\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n // URL matches expected pattern, use deleteFileByUrl\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n // Handle different types of errors\n if (error instanceof AppError) {\n return next(error);\n }\n // File doesn't exist or other error\n return next(new AppError(\"File not found\", 404));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Ensure upload directory exists\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n // Create directory if it doesn't exist\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n // Select the appropriate uploader service based on file type\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n // Handle the file upload\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n // Check if new file was uploaded\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n ) {\n return next(new AppError(\"No new file uploaded\", 400));\n }\n\n // Only attempt to delete old file if fileName is specified\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Check if the URL follows the expected format\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // URL matches expected pattern, use deleteFileByUrl\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n // Log the error but continue with upload - old file might not exist\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n // Process the new uploaded file(s)\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n // Process multiple image files with image transformations\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n // Just store other file types without processing\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n if (fileType === \"images\") {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n req.responseData = jsonContent;\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n streamFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n const { fileName, fileType } = req.params;\n\n const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n try {\n await fs.promises.access(filePath);\n } catch (err) {\n throw new AppError(\"File not found\", 404);\n }\n\n const fileStat = await fs.promises.stat(filePath);\n const fileSize = fileStat.size;\n const range = req.headers.range;\n\n if (range) {\n const [partialStart, partialEnd] = range\n .replace(/bytes=/, \"\")\n .split(\"-\");\n const start = parseInt(partialStart, 10) || 0;\n const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n if (start >= fileSize || end >= fileSize) {\n res.status(416).json({ error: \"Range Not Satisfiable\" });\n return;\n }\n\n res.writeHead(206, {\n \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n \"Accept-Ranges\": \"bytes\",\n \"Content-Length\": end - start + 1,\n \"Content-Type\": \"application/octet-stream\",\n \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n });\n\n fs.createReadStream(filePath, { start, end }).pipe(res);\n } else {\n res.writeHead(200, {\n \"Content-Length\": fileSize,\n \"Content-Type\": \"application/octet-stream\",\n \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n });\n fs.createReadStream(filePath).pipe(res);\n }\n }\n );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
|
|
1
|
+
{"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,+DAAiE;AAKjE,MAAM,oBAAoB;IAA1B;QAeE,eAAU,GAAG,IAAA,qBAAU,EACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,IAAI,CAAC,YAAY;gBACf,IAAA,oCAAmB,EAAC,aAAa,CAAC,EAAE,YAAY,IAAI,EAAE,CAAC;YAEzD,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAA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CAAC;wBAC1B,IAAI,GAAG,MAAM,IAAA,kCAAY,EAAC,GAAG,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;oBACzD,CAAC;yBAAM,CAAC;wBACN,IAAI,GAAG,MAAM,IAAA,iCAAW,EAAC,GAAG,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;oBAC/C,CAAC;gBACH,CAAC;gBAED,MAAM,WAAW,GAAG;oBAClB,OAAO,EAAE,IAAI;oBACb,IAAI;oBACJ,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;wBAC1B,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE;4BAClC,CAAC,CAAC,8BAA8B,IAAI,CAAC,MAAM,qBAAqB;4BAChE,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,8BAA8B;wBAChD,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE;4BAClC,CAAC,CAAC,2BAA2B;4BAC7B,CAAC,CAAC,4BAA4B;iBACnC,CAAC;gBAEF,IAAI,IAAI,CAAC,YAAY,CAAC,eAAe,EAAE,CAAC;oBACtC,GAAG,CAAC,YAAY,GAAG,WAAW,CAAC;oBAC/B,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;oBACzB,OAAO,IAAI,EAAE,CAAC;gBAChB,CAAC;gBAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IAqDJ,CAAC;CAAA;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nclass FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Ensure upload directory exists\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n // Create directory if it doesn't exist\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n // Select the appropriate uploader service based on file type\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n // Handle the file upload\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n // Process all uploaded files\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n // Process multiple image files with image transformations\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n // Just store other file types without processing\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n if (fileType === \"images\") {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(new AppError(\"No file uploaded\", 400));\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors?.afterUploadFile) {\n req.responseData = jsonContent;\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // This checks if the URL follows the expected format: /api/files/{fileType}/{fileName}\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n // URL matches expected pattern, use deleteFileByUrl\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n // Handle different types of errors\n if (error instanceof AppError) {\n return next(error);\n }\n // File doesn't exist or other error\n return next(new AppError(\"File not found\", 404));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Ensure upload directory exists\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n // Create directory if it doesn't exist\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\n\n // Select the appropriate uploader service based on file type\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n // Handle the file upload\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n // Check if new file was uploaded\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n ) {\n return next(new AppError(\"No new file uploaded\", 400));\n }\n\n // Only attempt to delete old file if fileName is specified\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Check if the URL follows the expected format\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // URL matches expected pattern, use deleteFileByUrl\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n // Log the error but continue with upload - old file might not exist\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n // Process the new uploaded file(s)\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n // Process multiple image files with image transformations\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n // Just store other file types without processing\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n if (fileType === \"images\") {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.interceptors.afterUpdateFile) {\n req.responseData = jsonContent;\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n // streamFile = catchAsync(\n // async (req: ArkosRequest, res: ArkosResponse, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(filePath);\n // const fileSize = fileStat.size;\n // const range = req.headers.range;\n\n // if (range) {\n // const [partialStart, partialEnd] = range\n // .replace(/bytes=/, \"\")\n // .split(\"-\");\n // const start = parseInt(partialStart, 10) || 0;\n // const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n // if (start >= fileSize || end >= fileSize) {\n // res.status(416).json({ error: \"Range Not Satisfiable\" });\n // return;\n // }\n\n // res.writeHead(206, {\n // \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n // \"Accept-Ranges\": \"bytes\",\n // \"Content-Length\": end - start + 1,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n\n // fs.createReadStream(filePath, { start, end }).pipe(res);\n // } else {\n // res.writeHead(200, {\n // \"Content-Length\": fileSize,\n // \"Content-Type\": \"application/octet-stream\",\n // \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n // });\n // fs.createReadStream(filePath).pipe(res);\n // }\n // }\n // );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
|