arkos 1.0.16 → 1.0.18-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/modules/base/base.router.js +1 -2
- package/dist/cjs/modules/base/base.router.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +19 -16
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +165 -159
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/es2020/modules/base/base.router.js +1 -2
- package/dist/es2020/modules/base/base.router.js.map +1 -1
- package/dist/es2020/modules/error-handler/error-handler.controller.js +19 -16
- package/dist/es2020/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/es2020/utils/helpers/models.helpers.js +159 -154
- package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
- package/dist/types/utils/helpers/models.helpers.d.ts +54 -22
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,0CAEC;AAoPD,4DAqIC;AAgCD,8CAgBC;AA0HD,0DAKC;AAmBgB,8BAAS;AAAE,oDAAoB;AA5kBhD,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6DAAoC;AACpC,6CAAiD;AAEtC,QAAA,mBAAmB,GAG1B,EAAE,CAAC;AAEP,SAAgB,eAAe,CAAC,SAAiB;IAC/C,OAAO,2BAAmB,CAAC,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AAoPD,SAAsB,wBAAwB,CAAC,SAAiB;;QAC9D,MAAM,cAAc,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC;QAC1D,MAAM,cAAc,GAAG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AAI,CAAC,IAAI,CAAC;oBAClB,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,SAAS;iBAChB,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,yBAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;IACnD,CAAC;AACH,CAAC;AAQD,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,yBAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,yBAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,MAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,gCAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport arkosEnv from \"../arkos-env\";\nimport { userFileExtension } from \"./fs.helpers\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\n// /**\n// * Dynamically imports model-specific modules like middlewares, auth configurations,\n// * prisma query options, and DTOs for a given model.\n// *\n// * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\").\n// * @returns {Promise<Object>} An object containing the imported modules: `middlewares`, `authConfigs`, `prismaQueryOptions`, and `dtos`.\n// */\n// export async function importPrismaModelModules(modelName: string) {\n// const kebabModelName = kebabCase(modelName);\n// const lowerModelName = modelName.toLowerCase();\n\n// const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n// const dtosDir = path.join(moduleDir, \"dtos\");\n// const schemasDir = path.join(moduleDir, \"schemas\");\n\n// const middlewaresFile = path.join(\n// moduleDir,\n// `${kebabModelName}.middlewares.${userFileExtension}`\n// );\n// const authConfigsFile = path.join(\n// moduleDir,\n// `${kebabModelName}.auth-configs.${userFileExtension}`\n// );\n// const prismaQueryOptionsFile = path.join(\n// moduleDir,\n// `${kebabModelName}.prisma-query-options.${userFileExtension}`\n// );\n\n// // Define DTO file paths\n// const modelDtoFile = path.join(\n// dtosDir,\n// `${lowerModelName}.dto.${userFileExtension}`\n// );\n// const createDtoFile = path.join(\n// dtosDir,\n// `create-${lowerModelName}.dto.${userFileExtension}`\n// );\n// const updateDtoFile = path.join(\n// dtosDir,\n// `update-${lowerModelName}.dto.${userFileExtension}`\n// );\n// const queryDtoFile = path.join(\n// dtosDir,\n// `query-${lowerModelName}.dto.${userFileExtension}`\n// );\n\n// const modelSchemaFile = path.join(\n// schemasDir,\n// `${lowerModelName}.schema.${userFileExtension}`\n// );\n// const createSchemaFile = path.join(\n// schemasDir,\n// `create-${lowerModelName}.schema.${userFileExtension}`\n// );\n// const updateSchemaFile = path.join(\n// schemasDir,\n// `update-${lowerModelName}.schema.${userFileExtension}`\n// );\n// const querySchemaFile = path.join(\n// schemasDir,\n// `query-${lowerModelName}.schema.${userFileExtension}`\n// );\n\n// const result: {\n// middlewares?: any;\n// authConfigs?: any;\n// prismaQueryOptions?: any;\n// dtos: {\n// create?: any;\n// update?: any;\n// query?: any;\n// model?: any;\n// };\n// schemas: {\n// create?: any;\n// update?: any;\n// query?: any;\n// model?: any;\n// };\n// } = {\n// dtos: {},\n// schemas: {},\n// };\n\n// try {\n// if (fs.existsSync(middlewaresFile)) {\n// const middlewareModule = await import(middlewaresFile);\n// result.middlewares = middlewareModule;\n// }\n// } catch (error) {\n// console.error(\n// `Error importing middlewares for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(authConfigsFile)) {\n// const authConfigsModule = await import(authConfigsFile);\n// result.authConfigs = authConfigsModule.default || authConfigsModule;\n// }\n// } catch (error) {\n// console.error(\n// `Error importing auth configs for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(prismaQueryOptionsFile)) {\n// const prismaQueryOptionsModule = await import(prismaQueryOptionsFile);\n// result.prismaQueryOptions =\n// prismaQueryOptionsModule.default || prismaQueryOptionsModule;\n// }\n// } catch (error) {\n// console.error(\n// `Error importing prisma query options for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// // Import DTOs\n// const pascalModelName = pascalCase(modelName);\n// try {\n// if (fs.existsSync(modelDtoFile)) {\n// const modelDtoModule = await import(modelDtoFile);\n// result.dtos.model =\n// modelDtoModule.default || modelDtoModule[`${pascalModelName}Dto`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing model main DTO for model \"${modelName} ${pascalModelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(createDtoFile)) {\n// const createDtoModule = await import(createDtoFile);\n// result.dtos.create =\n// createDtoModule.default ||\n// createDtoModule[`Create${pascalModelName}Dto`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing create DTO for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(updateDtoFile)) {\n// const updateDtoModule = await import(updateDtoFile);\n// result.dtos.update =\n// updateDtoModule.default ||\n// updateDtoModule[`Update${pascalModelName}Dto`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing update DTO for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(queryDtoFile)) {\n// const queryDtoModule = await import(queryDtoFile);\n// result.dtos.query =\n// queryDtoModule.default || queryDtoModule[`Query${pascalModelName}Dto`];\n// }\n// } catch (error) {\n// console.error(`Error importing query DTO for model \"${modelName}\":`, error);\n// }\n\n// try {\n// if (fs.existsSync(modelSchemaFile)) {\n// const modelSchemaModule = await import(modelSchemaFile);\n// result.dtos.model =\n// modelSchemaModule.default ||\n// modelSchemaModule[`${pascalModelName}Schema`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing create Schema for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(createSchemaFile)) {\n// const createSchemaModule = await import(createSchemaFile);\n// result.dtos.create =\n// createSchemaModule.default ||\n// createSchemaModule[`Create${pascalModelName}Schema`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing create Schema for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(updateSchemaFile)) {\n// const updateSchemaModule = await import(updateSchemaFile);\n// result.dtos.update =\n// updateSchemaModule.default ||\n// updateSchemaModule[`Update${pascalModelName}Schema`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing update Schema for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(querySchemaFile)) {\n// const querySchemaModule = await import(querySchemaFile);\n// result.dtos.query =\n// querySchemaModule.default ||\n// querySchemaModule[`Query${pascalModelName}Schema`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing query Schema for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// prismaModelsModules[modelName] = result;\n\n// return result;\n// }\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const lowerModelName = kebabModelName.toLowerCase();\n const pascalModelName = pascalCase(modelName);\n\n const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n\n // Define special auth module structure if needed\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Define the structure of files to import\n const fileStructure = {\n core: {\n service: `${kebabModelName}.service.${userFileExtension}`,\n controller: `${kebabModelName}.controller.${userFileExtension}`,\n middlewares: `${kebabModelName}.middlewares.${userFileExtension}`,\n authConfigs: `${kebabModelName}.auth-configs.${userFileExtension}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${userFileExtension}`,\n router: `${kebabModelName}.router.${userFileExtension}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${userFileExtension}`,\n signup: `signup.dto.${userFileExtension}`,\n updateMe: `update-me.dto.${userFileExtension}`,\n updatePassword: `update-password.dto.${userFileExtension}`,\n }\n : {\n model: `${lowerModelName}.dto.${userFileExtension}`,\n create: `create-${lowerModelName}.dto.${userFileExtension}`,\n update: `update-${lowerModelName}.dto.${userFileExtension}`,\n query: `query-${lowerModelName}.dto.${userFileExtension}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${userFileExtension}`,\n signup: `signup.schema.${userFileExtension}`,\n updateMe: `update-me.schema.${userFileExtension}`,\n updatePassword: `update-password.schema.${userFileExtension}`,\n }\n : {\n model: `${lowerModelName}.schema.${userFileExtension}`,\n create: `create-${lowerModelName}.schema.${userFileExtension}`,\n update: `update-${lowerModelName}.schema.${userFileExtension}`,\n query: `query-${lowerModelName}.schema.${userFileExtension}`,\n },\n };\n\n // Initialize result object\n const result: {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: any;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n } = {\n dtos: {},\n schemas: {},\n };\n\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n // For middlewares, keep the entire module\n if (key === \"middlewares\") result[key] = module;\n // For all other core files, prefer default export\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n\n // Process DTOs and schemas in parallel\n const processSubdir = async (type: \"dtos\" | \"schemas\") => {\n const subdir = path.join(moduleDir, type);\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n }\n };\n\n // Process both subdirectories in parallel\n await Promise.all([processSubdir(\"dtos\"), processSubdir(\"schemas\")]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\nconst schemaFolderPath =\n process.env.PRISMA_SCHEMA_PATH || arkosEnv.PRISMA_SCHEMA_PATH;\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nconst prismaModelRelationFields: Record<string, RelationFields> = {};\n\nconst prismaContent: string[] = [];\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\n// const prismaRootDir = \"\"; // Adjust this path if needed\nconst files = getAllPrismaFiles(\"./prisma\");\n\nfor (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n prismaContent.push(content);\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nconst models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nprismaContent.join(\"\\n\").replace(modelRegex, (_, modelName) => {\n if (!models.includes(modelName)) models.push(camelCase(modelName.trim()));\n return modelName;\n});\n\nfor (const model of models) {\n const modelName = pascalCase(model);\n\n let modelFile;\n for (const file of files) {\n const filePath = path.join(file);\n const stats = fs.statSync(filePath);\n\n if (stats.isFile()) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n prismaContent.push(content);\n if (content.includes(`model ${modelName} {`)) {\n modelFile = file;\n break;\n }\n }\n }\n\n if (!modelFile) {\n throw new Error(`Model ${modelName} not found`);\n }\n\n const content = fs.readFileSync(path.join(modelFile), \"utf-8\");\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine.includes(\"@unique\");\n\n if (isUnique)\n prismaModelsUniqueFields[model] = [\n ...(prismaModelsUniqueFields[model] || []),\n { name: fieldName, type, isUnique },\n ];\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine.includes(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models.includes(camelCase(cleanType || \"\"))\n ) {\n const modelStart = content.indexOf(`enum ${cleanType} {`);\n\n if (\n !cleanType ||\n modelStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n ) {\n continue;\n }\n\n if (!type?.includes(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n}\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { models, getModels, getModelUniqueFields, prismaModelRelationFields };\n"]}
|
|
1
|
+
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,0CAEC;AAED,4EAyCC;AAED,sCAwDC;AASD,4DA2CC;AA2BD,8CAgBC;AAOD,wDA2HC;AAUD,0DAKC;AA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KAAK,QAAQ;oBACtB,SAAS,KAAK,MAAM,EACpB,CAAC;oBACD,SAAS;gBACX,CAAC;gBAED,IAAI,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,QAAQ,CAAC,IAAI,CAAC,CAAA,EAAE,CAAC;oBAC1B,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;wBACtB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;wBAClB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,iCAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC;AAED,sBAAsB,EAAE,CAAC;AAQzB,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,iCAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,iCAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,cAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,gCAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { userFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const lowerModelName = kebabModelName.toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n return {\n core: {\n service: `${kebabModelName}.service.${userFileExtension}`,\n controller: `${kebabModelName}.controller.${userFileExtension}`,\n middlewares: `${kebabModelName}.middlewares.${userFileExtension}`,\n authConfigs: `${kebabModelName}.auth-configs.${userFileExtension}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${userFileExtension}`,\n router: `${kebabModelName}.router.${userFileExtension}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${userFileExtension}`,\n signup: `signup.dto.${userFileExtension}`,\n updateMe: `update-me.dto.${userFileExtension}`,\n updatePassword: `update-password.dto.${userFileExtension}`,\n }\n : {\n model: `${lowerModelName}.dto.${userFileExtension}`,\n create: `create-${lowerModelName}.dto.${userFileExtension}`,\n update: `update-${lowerModelName}.dto.${userFileExtension}`,\n query: `query-${lowerModelName}.dto.${userFileExtension}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${userFileExtension}`,\n signup: `signup.schema.${userFileExtension}`,\n updateMe: `update-me.schema.${userFileExtension}`,\n updatePassword: `update-password.schema.${userFileExtension}`,\n }\n : {\n model: `${lowerModelName}.schema.${userFileExtension}`,\n create: `create-${lowerModelName}.schema.${userFileExtension}`,\n update: `update-${lowerModelName}.schema.${userFileExtension}`,\n query: `query-${lowerModelName}.schema.${userFileExtension}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(\n process.cwd(),\n \"src\",\n \"modules\",\n kebabCase(modelName)\n );\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<Record<string, any>> {\n const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n\n const result: {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: any;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n } = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n if (module) {\n if (key === \"middlewares\") result[key] = module;\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch {}\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels(testName?: string) {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent.includes(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models.includes(modelName)) models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n // let modelFile;\n // for (const file of files) {\n // const filePath = path.join(file);\n // const stats = fs.statSync(filePath);\n\n // if (stats.isFile()) {\n // const content = fs.readFileSync(filePath, \"utf-8\");\n // prismaContent.push(content);\n // if (content.includes(`model ${modelName} {`)) {\n // modelFile = file;\n // break;\n // }\n // }\n // }\n\n // if (!modelFile) {\n // return;\n // }\n\n // const content = fs.readFileSync(path.join(modelFile), \"utf-8\");\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine.includes(\"@unique\");\n\n if (isUnique) {\n const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\n }\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine.includes(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models.includes(camelCase(cleanType || \"\"))\n ) {\n const modelStart = content.indexOf(`enum ${cleanType} {`);\n\n if (\n !cleanType ||\n modelStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n ) {\n continue;\n }\n\n if (!type?.includes(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n }\n}\n\ninitializePrismaModels();\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
@@ -15,8 +15,7 @@ import { setupRouters } from "./utils/helpers/base.router.helpers";
|
|
|
15
15
|
export function getPrismaModelsRouter(arkosConfigs) {
|
|
16
16
|
return __awaiter(this, void 0, void 0, function* () {
|
|
17
17
|
const router = Router();
|
|
18
|
-
|
|
19
|
-
yield Promise.all(setupRouters(models, router));
|
|
18
|
+
yield Promise.all(setupRouters(getModels(), router));
|
|
20
19
|
return router;
|
|
21
20
|
});
|
|
22
21
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.router.js","sourceRoot":"","sources":["../../../../src/modules/base/base.router.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,MAAM,oCAAoC,CAAC;AAE/D,OAAO,WAAW,MAAM,sBAAsB,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAEnE,MAAM,UAAgB,qBAAqB,CAAC,YAA0B;;QACpE,MAAM,MAAM,GAAW,MAAM,EAAE,CAAC;QAEhC,MAAM,
|
|
1
|
+
{"version":3,"file":"base.router.js","sourceRoot":"","sources":["../../../../src/modules/base/base.router.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,MAAM,oCAAoC,CAAC;AAE/D,OAAO,WAAW,MAAM,sBAAsB,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AAEnE,MAAM,UAAgB,qBAAqB,CAAC,YAA0B;;QACpE,MAAM,MAAM,GAAW,MAAM,EAAE,CAAC;QAEhC,MAAM,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;QAErD,OAAO,MAAM,CAAC;IAChB,CAAC;CAAA;AAED,MAAM,UAAU,oCAAoC;IAClD,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC;IAExB,MAAM,CAAC,GAAG,CACR,mBAAmB,EACnB,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,YAAY,EACzB,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,yBAAyB,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EACtD,iBAAiB,CAClB,CAAC;IAEF,MAAM,CAAC,GAAG,CACR,sBAAsB,EACtB,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,YAAY,EACzB,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,yBAAyB,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EACtD,qBAAqB,CACtB,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { getAvalibleRoutes, getAvailableResources } from \"./base.controller\";\nimport { getModels } from \"../../utils/helpers/models.helpers\";\n\nimport authService from \"../auth/auth.service\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport { setupRouters } from \"./utils/helpers/base.router.helpers\";\n\nexport async function getPrismaModelsRouter(arkosConfigs?: ArkosConfig) {\n const router: Router = Router();\n\n await Promise.all(setupRouters(getModels(), router));\n\n return router;\n}\n\nexport function getAvailableResourcesAndRoutesRouter(): Router {\n const router = Router();\n\n router.get(\n \"/available-routes\",\n authService?.authenticate,\n authService?.handleActionAccessControl({}, \"view\", \"\"),\n getAvalibleRoutes\n );\n\n router.get(\n \"/available-resources\",\n authService?.authenticate,\n authService?.handleActionAccessControl({}, \"view\", \"\"),\n getAvailableResources\n );\n\n return router;\n}\n"]}
|
|
@@ -51,36 +51,39 @@ function sendDevelopmentError(err, req, res) {
|
|
|
51
51
|
var _a;
|
|
52
52
|
console.error("[\x1b[31mERROR\x1b[0m]:", err);
|
|
53
53
|
if (req.originalUrl.startsWith("/api"))
|
|
54
|
-
|
|
54
|
+
res.status(err.statusCode).json({
|
|
55
55
|
message: err.message.split("\n")[err.message.split("\n").length - 1],
|
|
56
56
|
error: err,
|
|
57
57
|
stack: (_a = err.stack) === null || _a === void 0 ? void 0 : _a.split("\n"),
|
|
58
58
|
});
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
59
|
+
else
|
|
60
|
+
res.status(err.statusCode).json({
|
|
61
|
+
title: "Something went wrong!",
|
|
62
|
+
message: err.message,
|
|
63
|
+
});
|
|
63
64
|
}
|
|
64
65
|
function sendProductionError(err, req, res) {
|
|
65
66
|
if (req.originalUrl.startsWith("/api")) {
|
|
66
|
-
if (err.isOperational)
|
|
67
|
-
|
|
67
|
+
if (err.isOperational)
|
|
68
|
+
res.status(err.statusCode).json({
|
|
68
69
|
status: err.status,
|
|
69
70
|
message: err.message,
|
|
70
71
|
});
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
72
|
+
else
|
|
73
|
+
res.status(500).json({
|
|
74
|
+
status: "error",
|
|
75
|
+
message: "Something went wrong!",
|
|
76
|
+
});
|
|
77
|
+
return;
|
|
76
78
|
}
|
|
77
79
|
if (err.isOperational) {
|
|
78
|
-
|
|
80
|
+
res.status(err.statusCode).json({
|
|
79
81
|
title: "Something went wrong!",
|
|
80
82
|
message: err.message,
|
|
81
83
|
});
|
|
84
|
+
return;
|
|
82
85
|
}
|
|
83
|
-
|
|
86
|
+
res.status(err.statusCode).json({
|
|
84
87
|
title: "Something went wrong!",
|
|
85
88
|
message: "Please try again later.",
|
|
86
89
|
});
|
|
@@ -91,9 +94,9 @@ process.on("SIGTERM", () => {
|
|
|
91
94
|
process.exit();
|
|
92
95
|
}
|
|
93
96
|
else {
|
|
94
|
-
console.error("
|
|
97
|
+
console.error("SIGTERM RECEIVED in Production. Shutting down gracefully!");
|
|
95
98
|
server.close(() => {
|
|
96
|
-
console.error("
|
|
99
|
+
console.error("Process terminated!!!");
|
|
97
100
|
});
|
|
98
101
|
}
|
|
99
102
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AACzC,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiBtC,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,IAAkB;IAGlB,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAGnC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC1C,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;QACpC,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G,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,CACX,gEAAgE,CACjE,CAAC;QAEF,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n next: NextFunction\n): void {\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n // Handle general error types (e.g., syntax errors, type errors, etc.)\n // if (err.name === \"SyntaxError\")\n // error = errorControllerHelper.handleSchemaSyntaxError(err);\n // if (err.name === \"TypeError\")\n // error = errorControllerHelper.handleClientTypeError(err);\n // if (err.name === \"BinaryError\")\n // error = errorControllerHelper.handleBinaryError(err);\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n // if (err.name === \"UnhandledPromiseRejection\")\n // error = errorControllerHelper.handleUnhandledPromiseError(err);\n if (!err.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(err: AppError, req: Request, res: Response) {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n\n if (req.originalUrl.startsWith(\"/api\"))\n return res.status(err.statusCode).json({\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n error: err,\n stack: err.stack?.split(\"\\n\"),\n });\n\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) {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational) {\n return res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n });\n }\n\n return res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n }\n\n if (err.isOperational) {\n return res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n }\n\n return 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(\n \"👋🏽 SIGTERM RECEIVED in Production. Shutting down gracefully!\"\n );\n\n server.close(() => {\n console.error(\"🔥 Process terminated\");\n });\n }\n});\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings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AAE,uBAAuB;aACjC,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;SACrB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,yBAAyB;KACnC,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n next: NextFunction\n): void {\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n // Handle general error types (e.g., syntax errors, type errors, etc.)\n // if (err.name === \"SyntaxError\")\n // error = errorControllerHelper.handleSchemaSyntaxError(err);\n // if (err.name === \"TypeError\")\n // error = errorControllerHelper.handleClientTypeError(err);\n // if (err.name === \"BinaryError\")\n // error = errorControllerHelper.handleBinaryError(err);\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n // if (err.name === \"UnhandledPromiseRejection\")\n // error = errorControllerHelper.handleUnhandledPromiseError(err);\n if (!err.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 console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n error: err,\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 });\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 });\n }\n});\n"]}
|