arkos 1.2.28-test → 1.2.30-test
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/modules/auth/auth.router.js +1 -1
- package/dist/cjs/modules/auth/auth.router.js.map +1 -1
- package/dist/cjs/modules/base/base.service.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +2 -0
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/catch-async.js +1 -1
- package/dist/cjs/modules/error-handler/utils/catch-async.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +6 -0
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/cjs/modules/file-upload/file-upload.router.js +3 -2
- package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js +3 -2
- package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
- package/dist/cjs/server.js +2 -2
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +19 -17
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/generate.js +1 -1
- package/dist/cjs/utils/cli/generate.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-service-template.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-service-template.js.map +1 -1
- package/dist/cjs/utils/helpers/global.helpers.js +7 -19
- package/dist/cjs/utils/helpers/global.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +20 -8
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js +7 -4
- package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/esm/modules/auth/auth.router.js +1 -1
- package/dist/esm/modules/auth/auth.router.js.map +1 -1
- package/dist/esm/modules/base/base.service.js.map +1 -1
- package/dist/esm/modules/base/utils/helpers/base.router.helpers.js +1 -1
- package/dist/esm/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +2 -0
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/catch-async.js +1 -1
- package/dist/esm/modules/error-handler/utils/catch-async.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +5 -0
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/esm/modules/file-upload/file-upload.router.js +3 -2
- package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/esm/modules/swagger/swagger.router.js +1 -1
- package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js +3 -2
- package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
- package/dist/esm/server.js +2 -2
- package/dist/esm/server.js.map +1 -1
- package/dist/esm/utils/cli/dev.js +19 -17
- package/dist/esm/utils/cli/dev.js.map +1 -1
- package/dist/esm/utils/cli/generate.js +1 -1
- package/dist/esm/utils/cli/generate.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-service-template.js +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-service-template.js.map +1 -1
- package/dist/esm/utils/helpers/global.helpers.js +7 -19
- package/dist/esm/utils/helpers/global.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/models.helpers.js +19 -8
- package/dist/esm/utils/helpers/models.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/prisma.helpers.js +7 -4
- package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/types/modules/auth/auth.controller.d.ts +7 -7
- package/dist/types/modules/auth/auth.service.d.ts +1 -1
- package/dist/types/modules/base/base.controller.d.ts +9 -9
- package/dist/types/modules/base/base.service.d.ts +1 -1
- package/dist/types/modules/error-handler/utils/catch-async.d.ts +1 -1
- package/dist/types/modules/error-handler/utils/error-handler.helpers.d.ts +4 -0
- package/dist/types/modules/file-upload/file-upload.controller.d.ts +4 -4
- package/dist/types/modules/file-upload/file-upload.router.d.ts +1 -1
- package/dist/types/modules/swagger/utils/helpers/swagger.router.helpers.d.ts +1 -1
- package/dist/types/utils/helpers/models.helpers.d.ts +7 -4
- package/dist/types/utils/helpers/prisma.helpers.d.ts +1 -1
- package/package.json +2 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;AAkBA,0CAEC;AAED,4EAmDC;AAED,sCAgCC;AAsBD,8DA8CC;AAQD,oDAcC;AASD,4DAsDC;AA2BD,8CAgBC;AAQD,wDA+GC;AAUD,0DAOC;AAgBD,0DAEC;AAUQ,8BAAS;AAAE,oDAAoB;AAndxC,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6CAAyD;AACzD,qDAAgD;AAEhD,0DAAkE;AAGlE,IAAI,mBAAmB,GAGnB,EAAE,CAAC;AAEP,SAAgB,eAAe,CAAC,SAAiB;IAC/C,OAAO,mBAAmB,CAAC,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AAED,SAAgB,gCAAgC,CAAC,SAAiB;IAChE,MAAM,cAAc,GAAG,IAA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;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,cAAM,CAAC;AAChB,CAAC;AAOD,SAAgB,uBAAuB;IACrC,OAAO,4BAAoB,CAAC;AAC9B,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 { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { killServerChildProcess } from \"../cli/utils/cli.helpers\";\n\n// Must be exported to not cause problems on cjs\nlet 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 isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n authConfigsNew: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n prismaQueryOptionsNew: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n findOne: `find-one-${kebabModelName}.dto.${ext}`,\n findMany: `find-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n findOne: `find-one-${kebabModelName}.schema.${ext}`,\n findMany: `find-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\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(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const fileStructure = getFileModelModulesFileStructure(modelName);\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 importModule(filePath).catch(() => null);\n if (module) result[type][key] = module.default;\n } catch (error) {\n // Silent fail - file might not exist\n console.error(error);\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n console.error(error);\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: any;\n prismaQueryOptionsNew?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {importPrismaModelModulesReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\") {\n if (result.prismaQueryOptions) {\n killServerChildProcess();\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"prisma-query-options\",\n \"query\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"prismaQueryOptionsNew\") {\n if (result.prismaQueryOptions) {\n killServerChildProcess();\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"query\",\n \"prisma-query-options\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigs\") {\n if (result.authConfigs) {\n killServerChildProcess();\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth-configs\",\n \"auth\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigsNew\") {\n if (result.authConfigs) {\n killServerChildProcess();\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth\",\n \"auth-configs\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {importPrismaModelModulesReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n key: string,\n module: any,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\" || key === \"prismaQueryOptionsNew\") {\n result.prismaQueryOptions = module.default || module;\n } else if (key === \"authConfigs\" || key === \"authConfigsNew\") {\n result.authConfigs = module.default || module;\n } else if (key === \"middlewares\" || key === \"router\") {\n result[key] = module;\n } else {\n result[key as keyof typeof result] = module.default || module;\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<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n if (getModelModules(modelName)) return getModelModules(modelName);\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\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 importModule(filePath).catch((err) => {\n if (!err.message.includes(\"Cannot find module\")) {\n console.error(`Failed to import ${fileName}: \\n`);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n });\n\n if (module) {\n // Validate naming conventions before assignment\n validateNamingConventions(key, fileName, result);\n\n // Assign module to result\n assignModuleToResult(key, module, result);\n }\n } catch (err: any) {\n if (err.message.includes(\"Cannot use both\")) throw err;\n console.error(err);\n killServerChildProcess();\n }\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Removed because caused problems with cached ZObjects\n // Cache the result making shallow copy to not cause problems after build\n // prismaModelsModules[modelName] = JSON.parse(JSON.stringify(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 let prismaSchemasContent: string;\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels() {\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 // Gather the content of all *.prisma files into single one\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n const copiedContent = content;\n prismaSchemasContent = content;\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n const modelStart = copiedContent.indexOf(`model ${modelName} {`);\n const modelEnd = copiedContent.indexOf(\"}\", modelStart);\n const modelDefinition = copiedContent.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 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 enumStart = copiedContent.indexOf(`enum ${cleanType} {`);\n const typeStart = copiedContent.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 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// initializePrismaModels();\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(\n modelName: string\n): RelationFields | undefined {\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(): string[] {\n return models;\n}\n\n/**\n * Returns all content of all .prisma files gathered together\n *\n * @returns {string}\n */\nexport function getPrismaSchemasContent(): string {\n return prismaSchemasContent;\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): ModelFieldDefition[] {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
1
|
+
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;AAkBA,0CAEC;AAED,0CAEC;AAED,4EAmDC;AAED,sCAkCC;AAsBD,8DA8CC;AAQD,oDAcC;AASD,4DA+DC;AA2BD,8CAgBC;AAQD,wDA+GC;AAQD,0DAOC;AAgBD,0DAEC;AAUQ,8BAAS;AAAE,oDAAoB;AAhexC,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6CAAyD;AACzD,qDAAgD;AAEhD,0DAAkE;AAMlE,IAAI,mBAAmB,GAAgC,EAAE,CAAC;AAE1D,SAAgB,eAAe,CAAC,SAAiB,EAAE,OAAoB;IACrE,mBAAmB,CAAC,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,GAAG,OAAO,CAAC;AACtD,CAAC;AAED,SAAgB,eAAe,CAAC,SAAiB;IAC/C,OAAO,mBAAmB,CAAC,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AAED,SAAgB,gCAAgC,CAAC,SAAiB;IAChE,MAAM,cAAc,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC;IAC1D,MAAM,YAAY,GAAG,SAAS,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;IACxD,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;IAEnC,OAAO;QACL,IAAI,EAAE;YACJ,OAAO,EAAE,GAAG,cAAc,YAAY,GAAG,EAAE;YAC3C,UAAU,EAAE,GAAG,cAAc,eAAe,GAAG,EAAE;YACjD,WAAW,EAAE,GAA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ChB,OAAO,cAAM,CAAC;AAChB,CAAC;AAOD,SAAgB,uBAAuB;IACrC,OAAO,4BAAoB,CAAC;AAC9B,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 { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { killServerChildProcess } from \"../cli/utils/cli.helpers\";\nimport { ArkosConfig } from \"../../exports\";\n\ntype ModeModules = Awaited<ReturnType<typeof importPrismaModelModules>>;\n\n// Must be exported to not cause problems on cjs\nlet prismaModelsModules: Record<string, ModeModules> = {};\n\nexport function setModelModules(modelName: string, modules: ModeModules) {\n prismaModelsModules[kebabCase(modelName)] = modules;\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 isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n authConfigsNew: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n prismaQueryOptionsNew: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n findOne: `find-one-${kebabModelName}.dto.${ext}`,\n findMany: `find-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n findOne: `find-one-${kebabModelName}.schema.${ext}`,\n findMany: `find-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\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(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const fileStructure = getFileModelModulesFileStructure(modelName);\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 importModule(filePath).catch(() => null);\n if (module) result[key] = module.default;\n } catch (error) {\n // Silent fail - file might not exist\n console.error(error);\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n console.error(error);\n }\n\n return result;\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: any;\n prismaQueryOptionsNew?: any;\n router?: any;\n dtos?: Record<string, any>;\n schemas?: Record<string, any>;\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {importPrismaModelModulesReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\") {\n if (result.prismaQueryOptions) {\n killServerChildProcess();\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"prisma-query-options\",\n \"query\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"prismaQueryOptionsNew\") {\n if (result.prismaQueryOptions) {\n killServerChildProcess();\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"query\",\n \"prisma-query-options\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigs\") {\n if (result.authConfigs) {\n killServerChildProcess();\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth-configs\",\n \"auth\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigsNew\") {\n if (result.authConfigs) {\n killServerChildProcess();\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth\",\n \"auth-configs\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {importPrismaModelModulesReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n key: string,\n module: any,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\" || key === \"prismaQueryOptionsNew\") {\n result.prismaQueryOptions = module.default || module;\n } else if (key === \"authConfigs\" || key === \"authConfigsNew\") {\n result.authConfigs = module.default || module;\n } else if (key === \"middlewares\" || key === \"router\") {\n result[key] = module;\n } else {\n result[key as keyof typeof result] = module.default || module;\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 arkosConfig: ArkosConfig\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n if (getModelModules(modelName)) return getModelModules(modelName);\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\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 importModule(filePath).catch((err) => {\n if (!err.message.includes(\"Cannot find module\")) {\n console.error(`Failed to import ${fileName}: \\n`);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n });\n\n if (module) {\n // Validate naming conventions before assignment\n validateNamingConventions(key, fileName, result);\n\n // Assign module to result\n assignModuleToResult(key, module, result);\n }\n } catch (err: any) {\n if (err.message.includes(\"Cannot use both\")) throw err;\n console.error(err);\n killServerChildProcess();\n }\n })\n );\n\n const validationSubdir = arkosConfig.validation?.resolver\n ? arkosConfig.validation.resolver === \"zod\"\n ? \"schemas\"\n : \"dtos\"\n : null;\n\n let validators = {};\n if (validationSubdir)\n validators = await processSubdir(modelName, validationSubdir);\n\n // Removed because caused problems with cached ZObjects\n // Cache the result making shallow copy to not cause problems after build\n // prismaModelsModules[modelName] = JSON.parse(JSON.stringify(result));\n prismaModelsModules[modelName] = {\n ...result,\n ...(validationSubdir && { [validationSubdir]: validators }),\n };\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 let prismaSchemasContent: string;\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels() {\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 // Gather the content of all *.prisma files into single one\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n const copiedContent = content;\n prismaSchemasContent = content;\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n const modelStart = copiedContent.indexOf(`model ${modelName} {`);\n const modelEnd = copiedContent.indexOf(\"}\", modelStart);\n const modelDefinition = copiedContent.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 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 enumStart = copiedContent.indexOf(`enum ${cleanType} {`);\n const typeStart = copiedContent.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 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/**\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(\n modelName: string\n): RelationFields | undefined {\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(): string[] {\n return models;\n}\n\n/**\n * Returns all content of all .prisma files gathered together\n *\n * @returns {string}\n */\nexport function getPrismaSchemasContent(): string {\n return prismaSchemasContent;\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): ModelFieldDefition[] {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
@@ -16,17 +16,20 @@ async function loadPrismaModule() {
|
|
|
16
16
|
if (!exports.prismaInstance) {
|
|
17
17
|
try {
|
|
18
18
|
let prismaPath = `${(0, fs_helpers_1.crd)()}/src/utils/prisma.${(0, fs_helpers_1.getUserFileExtension)()}`;
|
|
19
|
-
if (!fs_1.default.existsSync(prismaPath))
|
|
19
|
+
if (!fs_1.default.existsSync(prismaPath))
|
|
20
20
|
prismaPath = `${(0, fs_helpers_1.crd)()}/src/utils/prisma/index.${(0, fs_helpers_1.getUserFileExtension)()}`;
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
if (!fs_1.default.existsSync(prismaPath))
|
|
22
|
+
throw new Error("Could not found exported prisma insteance");
|
|
23
|
+
const prismaModule = await (0, global_helpers_1.importModule)(prismaPath, {
|
|
24
|
+
fixExtension: false,
|
|
25
|
+
});
|
|
23
26
|
exports.prismaInstance = prismaModule.default || prismaModule.prisma;
|
|
24
27
|
if (!exports.prismaInstance)
|
|
25
28
|
throw new Error("Prisma not found");
|
|
26
29
|
}
|
|
27
30
|
catch (error) {
|
|
28
31
|
if (error.message === "Prisma not found")
|
|
29
|
-
throw new app_error_1.default(`Could not initialize Prisma module. Make sure your prisma instance is exported under src/utils/prisma.${(0, fs_helpers_1.getUserFileExtension)()} or src/utils/prisma/index.${(0, fs_helpers_1.getUserFileExtension)()}, read more about Arkos' Project Structure under https://www.arkosjs.com/docs/project-structure#root-structure`, 500, {}, "
|
|
32
|
+
throw new app_error_1.default(`Could not initialize Prisma module. Make sure your prisma instance is exported under src/utils/prisma.${(0, fs_helpers_1.getUserFileExtension)()} or src/utils/prisma/index.${(0, fs_helpers_1.getUserFileExtension)()}, read more about Arkos' Project Structure under https://www.arkosjs.com/docs/project-structure#root-structure`, 500, {}, "PrismaInstanceNotFound");
|
|
30
33
|
throw error;
|
|
31
34
|
}
|
|
32
35
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prisma.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/prisma.helpers.ts"],"names":[],"mappings":";;;;;;AASA,
|
|
1
|
+
{"version":3,"file":"prisma.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/prisma.helpers.ts"],"names":[],"mappings":";;;;;;AASA,4CA6BC;AAED,8CAEC;AA1CD,4CAAoB;AAEpB,gGAAuE;AACvE,4FAAmE;AACnE,6CAAgE;AAChE,qDAAgD;AAErC,QAAA,cAAc,GAAQ,IAAI,CAAC;AAE/B,KAAK,UAAU,gBAAgB;IACpC,IAAI,CAAC,sBAAc,EAAE,CAAC;QACpB,IAAI,CAAC;YACH,IAAI,UAAU,GAAG,GAAG,IAAA,gBAAG,GAAE,qBAAqB,IAAA,iCAAG,GAAE,EAAE,CAAC;YAEtD,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC;gBAC5B,UAAU,GAAG,GAAG,IAAA,gBAAG,GAAE,2BAA2B,IAAA,iCAAG,GAAE,EAAE,CAAC;YAE1D,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,UAAU,CAAC;gBAC5B,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;YAE/D,MAAM,YAAY,GAAG,MAAM,IAAA,6BAAY,EAAC,UAAU,EAAE;gBAClD,YAAY,EAAE,KAAK;aACpB,CAAC,CAAC;YACH,sBAAc,GAAG,YAAY,CAAC,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC;YAE7D,IAAI,CAAC,sBAAc;gBAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;QAC3D,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,IAAI,KAAK,CAAC,OAAO,KAAK,kBAAkB;gBACtC,MAAM,IAAI,mBAAQ,CAChB,yGAAyG,IAAA,iCAAG,GAAE,8BAA8B,IAAA,iCAAG,GAAE,gHAAgH,EACjQ,GAAG,EACH,EAAE,EACF,wBAAwB,CACzB,CAAC;YACJ,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,sBAAc,CAAC;AACxB,CAAC;AAED,SAAgB,iBAAiB;IAC/B,OAAO,sBAAc,CAAC;AACxB,CAAC;AAEY,QAAA,uBAAuB,GAAG,IAAA,qBAAU,EAC/C,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IACxD,MAAM,MAAM,GAAG,MAAM,gBAAgB,EAAE,CAAC;IACxC,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,QAAQ,EAAE,CAAC;QACxB,IAAI,EAAE,CAAC;IACT,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,CAAC,IAAI,mBAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IACzC,CAAC;AACH,CAAC,CACF,CAAC","sourcesContent":["import fs from \"fs\";\nimport { Request, Response, NextFunction } from \"express\";\nimport catchAsync from \"../../modules/error-handler/utils/catch-async\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { crd, getUserFileExtension as ext } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\n\nexport let prismaInstance: any = null;\n\nexport async function loadPrismaModule() {\n if (!prismaInstance) {\n try {\n let prismaPath = `${crd()}/src/utils/prisma.${ext()}`;\n\n if (!fs.existsSync(prismaPath))\n prismaPath = `${crd()}/src/utils/prisma/index.${ext()}`;\n\n if (!fs.existsSync(prismaPath))\n throw new Error(\"Could not found exported prisma insteance\");\n\n const prismaModule = await importModule(prismaPath, {\n fixExtension: false,\n });\n prismaInstance = prismaModule.default || prismaModule.prisma;\n\n if (!prismaInstance) throw new Error(\"Prisma not found\");\n } catch (error: any) {\n if (error.message === \"Prisma not found\")\n throw new AppError(\n `Could not initialize Prisma module. Make sure your prisma instance is exported under src/utils/prisma.${ext()} or src/utils/prisma/index.${ext()}, read more about Arkos' Project Structure under https://www.arkosjs.com/docs/project-structure#root-structure`,\n 500,\n {},\n \"PrismaInstanceNotFound\"\n );\n throw error;\n }\n }\n return prismaInstance;\n}\n\nexport function getPrismaInstance() {\n return prismaInstance;\n}\n\nexport const checkDatabaseConnection = catchAsync(\n async (req: Request, res: Response, next: NextFunction) => {\n const prisma = await loadPrismaModule();\n try {\n await prisma.$connect();\n next();\n } catch (error: any) {\n console.error(\"Database connection error\", error.message);\n next(new AppError(error.message, 503));\n }\n }\n);\n"]}
|
|
@@ -8,7 +8,7 @@ import deepmerge from "../../utils/helpers/deepmerge.helper.js";
|
|
|
8
8
|
import catchAsync from "../error-handler/utils/catch-async.js";
|
|
9
9
|
const router = Router();
|
|
10
10
|
export async function getAuthRouter(arkosConfigs) {
|
|
11
|
-
const { middlewares, dtos, schemas, prismaQueryOptions } = await importPrismaModelModules("auth");
|
|
11
|
+
const { middlewares, dtos, schemas, prismaQueryOptions } = await importPrismaModelModules("auth", arkosConfigs);
|
|
12
12
|
const authController = await authControllerFactory(middlewares);
|
|
13
13
|
const getValidationSchemaOrDto = (key) => {
|
|
14
14
|
const validationConfigs = arkosConfigs?.validation;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.router.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.router.ts"],"names":[],"mappings":"AAAA,OAA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,WAAW,EAAE,YAAY,CAAC;YACzC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC;YACtC,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC;YAC1C,CAAC,CAAC,YAAY;QAChB,YAAY;KACb,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CACvC,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,uBAAuB,EACvB,WAAW,CAAC,YAAY,EACxB,4CAA4C,CAC1C,wBAAwB,CAAC,gBAAgB,CAAC,CAC3C,EACD,8BAA8B,CAC5B,kBAAiD,EACjD,gBAAgB,CACjB,EACD,GAAG;QACD,cAAc,CAAC,WAAW,EAAE,oBAAoB,CAAC;YAC/C,cAAc,CAAC,cAAc;QAC/B,cAAc,CAAC,WAAW,EAAE,oBAAoB,CAAC;YAC/C,CAAC,CAAC,cAAc,CAAC,cAAc;YAC/B,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,mBAAmB,CAAC,IAAI,YAAY;QACpE,cAAc,CAAC,WAAW,EAAE,oBAAoB,CAAC;YACjD,cAAc,CAAC,WAAW,EAAE,mBAAmB,CAAC;YAC9C,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,mBAAmB,CAAC;YAClD,CAAC,CAAC,YAAY;QAChB,YAAY;KACb,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CACvC,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { authControllerFactory } from \"./auth.controller\";\nimport authService from \"./auth.service\";\nimport rateLimit from \"express-rate-limit\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../base/base.middlewares\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthPrismaQueryOptions } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\n\nconst router: Router = Router();\n\nexport async function getAuthRouter(arkosConfigs: ArkosConfig) {\n const { middlewares, dtos, schemas, prismaQueryOptions } =\n await importPrismaModelModules(\"auth\");\n const authController = await authControllerFactory(middlewares);\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (key: string) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // Helper to conditionally wrap middleware with catchAsync\n const safeCatchAsync = (middleware: any) => {\n return middleware ? catchAsync(middleware) : undefined;\n };\n\n router\n .get(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"getMe\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeGetMe) || authController.getMe,\n safeCatchAsync(middlewares?.beforeGetMe)\n ? authController.getMe\n : safeCatchAsync(middlewares?.afterGetMe) || sendResponse,\n safeCatchAsync(middlewares?.beforeGetMe) &&\n safeCatchAsync(middlewares?.afterGetMe)\n ? safeCatchAsync(middlewares?.afterGetMe)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n )\n .patch(\n \"/users/me\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMe\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updateMe\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdateMe) || authController.updateMe,\n safeCatchAsync(middlewares?.beforeUpdateMe)\n ? authController.updateMe\n : safeCatchAsync(middlewares?.afterUpdateMe) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdateMe) &&\n safeCatchAsync(middlewares?.afterUpdateMe)\n ? safeCatchAsync(middlewares?.afterUpdateMe)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n )\n .delete(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"deleteMe\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeDeleteMe) || authController.deleteMe,\n safeCatchAsync(middlewares?.beforeDeleteMe)\n ? authController.deleteMe\n : safeCatchAsync(middlewares?.afterDeleteMe) || sendResponse,\n safeCatchAsync(middlewares?.beforeDeleteMe) &&\n safeCatchAsync(middlewares?.afterDeleteMe)\n ? safeCatchAsync(middlewares?.afterDeleteMe)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.use(\n \"/auth\",\n rateLimit(\n deepmerge(\n {\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (req, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfigs?.authentication?.requestRateLimitOptions || {}\n )\n )\n );\n\n router.post(\n \"/auth/login\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"login\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"login\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeLogin) || authController.login,\n safeCatchAsync(middlewares?.beforeLogin)\n ? authController.login\n : safeCatchAsync(middlewares?.afterLogin) || sendResponse,\n safeCatchAsync(middlewares?.beforeLogin) &&\n safeCatchAsync(middlewares?.afterLogin)\n ? safeCatchAsync(middlewares?.afterLogin)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.delete(\n \"/auth/logout\",\n authService.authenticate,\n ...[\n safeCatchAsync(middlewares?.beforeLogout) || authController.logout,\n safeCatchAsync(middlewares?.beforeLogout)\n ? authController.logout\n : safeCatchAsync(middlewares?.afterLogout) || sendResponse,\n safeCatchAsync(middlewares?.beforeLogout) &&\n safeCatchAsync(middlewares?.afterLogout)\n ? safeCatchAsync(middlewares?.afterLogout)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.post(\n \"/auth/signup\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"signup\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"signup\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeSignup) || authController.signup,\n safeCatchAsync(middlewares?.beforeSignup)\n ? authController.signup\n : safeCatchAsync(middlewares?.afterSignup) || sendResponse,\n safeCatchAsync(middlewares?.beforeSignup) &&\n safeCatchAsync(middlewares?.afterSignup)\n ? safeCatchAsync(middlewares?.afterSignup)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.post(\n \"/auth/update-password\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updatePassword\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updatePassword\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdatePassword) ||\n authController.updatePassword,\n safeCatchAsync(middlewares?.beforeUpdatePassword)\n ? authController.updatePassword\n : safeCatchAsync(middlewares?.afterUpdatePassword) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdatePassword) &&\n safeCatchAsync(middlewares?.afterUpdatePassword)\n ? safeCatchAsync(middlewares?.afterUpdatePassword)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n return router;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auth.router.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAA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C,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC;YAC1C,CAAC,CAAC,YAAY;QAChB,YAAY;KACb,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CACvC,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,uBAAuB,EACvB,WAAW,CAAC,YAAY,EACxB,4CAA4C,CAC1C,wBAAwB,CAAC,gBAAgB,CAAC,CAC3C,EACD,8BAA8B,CAC5B,kBAAiD,EACjD,gBAAgB,CACjB,EACD,GAAG;QACD,cAAc,CAAC,WAAW,EAAE,oBAAoB,CAAC;YAC/C,cAAc,CAAC,cAAc;QAC/B,cAAc,CAAC,WAAW,EAAE,oBAAoB,CAAC;YAC/C,CAAC,CAAC,cAAc,CAAC,cAAc;YAC/B,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,mBAAmB,CAAC,IAAI,YAAY;QACpE,cAAc,CAAC,WAAW,EAAE,oBAAoB,CAAC;YACjD,cAAc,CAAC,WAAW,EAAE,mBAAmB,CAAC;YAC9C,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,mBAAmB,CAAC;YAClD,CAAC,CAAC,YAAY;QAChB,YAAY;KACb,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CACvC,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { authControllerFactory } from \"./auth.controller\";\nimport authService from \"./auth.service\";\nimport rateLimit from \"express-rate-limit\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../base/base.middlewares\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthPrismaQueryOptions } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\n\nconst router: Router = Router();\n\nexport async function getAuthRouter(arkosConfigs: ArkosConfig) {\n const { middlewares, dtos, schemas, prismaQueryOptions } =\n await importPrismaModelModules(\"auth\", arkosConfigs);\n const authController = await authControllerFactory(middlewares);\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (key: string) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // Helper to conditionally wrap middleware with catchAsync\n const safeCatchAsync = (middleware: any) => {\n return middleware ? catchAsync(middleware) : undefined;\n };\n\n router\n .get(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"getMe\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeGetMe) || authController.getMe,\n safeCatchAsync(middlewares?.beforeGetMe)\n ? authController.getMe\n : safeCatchAsync(middlewares?.afterGetMe) || sendResponse,\n safeCatchAsync(middlewares?.beforeGetMe) &&\n safeCatchAsync(middlewares?.afterGetMe)\n ? safeCatchAsync(middlewares?.afterGetMe)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n )\n .patch(\n \"/users/me\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMe\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updateMe\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdateMe) || authController.updateMe,\n safeCatchAsync(middlewares?.beforeUpdateMe)\n ? authController.updateMe\n : safeCatchAsync(middlewares?.afterUpdateMe) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdateMe) &&\n safeCatchAsync(middlewares?.afterUpdateMe)\n ? safeCatchAsync(middlewares?.afterUpdateMe)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n )\n .delete(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"deleteMe\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeDeleteMe) || authController.deleteMe,\n safeCatchAsync(middlewares?.beforeDeleteMe)\n ? authController.deleteMe\n : safeCatchAsync(middlewares?.afterDeleteMe) || sendResponse,\n safeCatchAsync(middlewares?.beforeDeleteMe) &&\n safeCatchAsync(middlewares?.afterDeleteMe)\n ? safeCatchAsync(middlewares?.afterDeleteMe)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.use(\n \"/auth\",\n rateLimit(\n deepmerge(\n {\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (req, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfigs?.authentication?.requestRateLimitOptions || {}\n )\n )\n );\n\n router.post(\n \"/auth/login\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"login\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"login\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeLogin) || authController.login,\n safeCatchAsync(middlewares?.beforeLogin)\n ? authController.login\n : safeCatchAsync(middlewares?.afterLogin) || sendResponse,\n safeCatchAsync(middlewares?.beforeLogin) &&\n safeCatchAsync(middlewares?.afterLogin)\n ? safeCatchAsync(middlewares?.afterLogin)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.delete(\n \"/auth/logout\",\n authService.authenticate,\n ...[\n safeCatchAsync(middlewares?.beforeLogout) || authController.logout,\n safeCatchAsync(middlewares?.beforeLogout)\n ? authController.logout\n : safeCatchAsync(middlewares?.afterLogout) || sendResponse,\n safeCatchAsync(middlewares?.beforeLogout) &&\n safeCatchAsync(middlewares?.afterLogout)\n ? safeCatchAsync(middlewares?.afterLogout)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.post(\n \"/auth/signup\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"signup\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"signup\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeSignup) || authController.signup,\n safeCatchAsync(middlewares?.beforeSignup)\n ? authController.signup\n : safeCatchAsync(middlewares?.afterSignup) || sendResponse,\n safeCatchAsync(middlewares?.beforeSignup) &&\n safeCatchAsync(middlewares?.afterSignup)\n ? safeCatchAsync(middlewares?.afterSignup)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.post(\n \"/auth/update-password\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updatePassword\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updatePassword\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdatePassword) ||\n authController.updatePassword,\n safeCatchAsync(middlewares?.beforeUpdatePassword)\n ? authController.updatePassword\n : safeCatchAsync(middlewares?.afterUpdatePassword) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdatePassword) &&\n safeCatchAsync(middlewares?.afterUpdatePassword)\n ? safeCatchAsync(middlewares?.afterUpdatePassword)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n return router;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,GACX,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,SAAS,EACT,uBAAuB,GAExB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,SA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AS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,UAAU,CAGvC,CACF,CAAC;IACJ,CAAC;IAQD,KAAK,CAAC,SAAS,CACb,OAKO;QAEP,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAC;QAEnC,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,MAAM,CAAC;YAC5D,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC;IAQD,KAAK,CAAC,UAAU,CACd,OAKuB;QAEvB,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAC;QAEnC,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,UAAU,CAAC;YAChE,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC;CACF;AAOD,MAAM,UAAU,eAAe;IAC7B,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,YAAY,GAAqC,EAAE,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport {\n getModels,\n getPrismaModelRelations,\n RelationFields,\n} from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { handleRelationFieldsInBody } from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n *\n * by model-specific service classes.\n *\n * @class BaseService\n *\n * @usage\n *\n * **Example:** creating a simple service\n *\n * ```ts\n * import { prisma } from '../../utils/prisma'\n *\n * const userService = new BaseService<typeof prisma.user>(\"user\")\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-service-class}\n *\n */\nexport class BaseService<ModelDelegate extends Record<string, any> = any> {\n /**\n * The camelCase name of the model\n * @public\n */\n modelName: string;\n\n /**\n * Object containing singular and list relation fields for the model\n * @public\n */\n relationFields: RelationFields;\n\n /**\n * Instance of the Prisma client\n * @public\n */\n prisma: any;\n\n /**\n * Creates an instance of BaseService.\n * @param {string} modelName - The name of the model to perform operations on.\n */\n constructor(modelName: string) {\n this.modelName = camelCase(modelName);\n this.relationFields = getPrismaModelRelations(pascalCase(modelName))!;\n }\n\n /**\n * Creates a single record in the database.\n *\n * @param {Parameters<ModelDelegate[\"create\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to create the record with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"create\"]>>} The created record.\n */\n async createOne<\n TOptions extends Omit<Parameters<ModelDelegate[\"create\"]>[0], \"data\">,\n >(\n data: Parameters<ModelDelegate[\"create\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"create\"] extends (args: { data: any }) => infer R ? R : any\n > {\n // user uer Password123 true false Promise { true }\n if (kebabCase(this.modelName) === \"user\" && (data as any).password)\n if (!authService.isPasswordHashed((data as any).password))\n (data as any).password = await authService.hashPassword(\n (data as any).password\n );\n\n const prisma = getPrismaInstance();\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(\n data as Record<string, any>,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n return await (prisma[this.modelName] as ModelDelegate).create(\n deepmerge(\n {\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { data: any }\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Parameters<ModelDelegate[\"createMany\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - An array of data to create records with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"createMany\"]>>} The result of the createMany operation.\n */\n async createMany<\n TOptions extends Omit<Parameters<ModelDelegate[\"createMany\"]>[0], \"data\">,\n >(\n data: Parameters<ModelDelegate[\"createMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"createMany\"] extends (args: { data: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n const dataWithRelationFieldsHandled: any[] = [];\n\n if (Array.isArray(data))\n await new Promise((resolve) => {\n (data as { [x: string]: any; password?: string }[]).forEach(\n async (curr, i) => {\n if (\"password\" in curr && this.modelName === \"user\")\n if (!authService.isPasswordHashed(curr.password!))\n data[i].password = await authService.hashPassword(\n curr?.password!\n );\n\n dataWithRelationFieldsHandled[i] = handleRelationFieldsInBody(\n data[i] as Record<string, any>,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n if (i === data.length - 1) resolve(null);\n }\n );\n });\n\n return await (prisma[this.modelName] as ModelDelegate).createMany(\n deepmerge(\n { data: dataWithRelationFieldsHandled },\n (queryOptions as {}) || {}\n ) as {\n data: any;\n }\n );\n }\n\n /**\n * Counts records based on provided filters.\n *\n * @param {Parameters<ModelDelegate[\"count\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to apply to the query.\n * @returns {Promise<number>} The count of records matching the filters.\n */\n async count(\n filters: Parameters<ModelDelegate[\"count\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<number> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).count({\n where: filters,\n });\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Parameters<ModelDelegate[\"findMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to apply to the query.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findMany\"]>>} The found data.\n */\n async findMany<\n TOptions extends Omit<Parameters<ModelDelegate[\"findMany\"]>[0], \"where\">,\n >(\n filters: Parameters<ModelDelegate[\"findMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findMany\"] extends (\n args: { where: any } & TOptions\n ) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).findMany(\n deepmerge({ where: filters }, (queryOptions as {}) || {}) as {\n where: any;\n } & TOptions\n );\n }\n\n /**\n * Finds a single record by its ID.\n *\n * @param {string | number} id - The ID of the record to find.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findUnique\"]>>} The found record or null if not found.\n */\n async findById<\n TOptions extends Omit<Parameters<ModelDelegate[\"findUnique\"]>[0], \"where\">,\n >(\n id: string | number,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findUnique\"] extends (args: { where: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).findUnique(\n deepmerge(\n {\n where: { id },\n },\n queryOptions || {}\n ) as { where: { id: string | number } }\n );\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Parameters<ModelDelegate[\"findFirst\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any | Parameters<TModel[\"findUnique\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findOne<\n TOptions extends\n | Omit<Parameters<ModelDelegate[\"findFirst\"]>[0], \"where\">\n | Omit<Parameters<ModelDelegate[\"findUnique\"]>[0], \"where\">,\n >(\n filters: Parameters<ModelDelegate[\"findFirst\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any | Parameters<ModelDelegate[\"findUnique\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findFirst\"] extends (args: { where: any }) => infer R\n ? R\n : ModelDelegate[\"findUnique\"] extends (args: { where: any }) => infer R2\n ? R2\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (\n Object.keys(filters as Record<string, any>).length === 1 &&\n \"id\" in (filters as Record<string, any>) &&\n (filters as any).id !== \"me\"\n )\n return (prisma[this.modelName] as ModelDelegate).findUnique(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).findFirst(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any }\n );\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Parameters<ModelDelegate[\"update\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {Parameters<ModelDelegate[\"update\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to update the record with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"update\"]>>} The updated record or null if not found.\n */\n async updateOne<\n TOptions extends Omit<\n Parameters<ModelDelegate[\"update\"]>[0],\n \"where\" | \"data\"\n >,\n >(\n filters: Parameters<ModelDelegate[\"update\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<ModelDelegate[\"update\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"update\"] extends (args: { where: any; data: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && (data as any)?.password) {\n if (!authService.isPasswordHashed((data as any).password!))\n (data as any).password = await authService.hashPassword(\n (data as any)?.password\n );\n }\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(\n data as Record<string, any>,\n {\n ...this.relationFields,\n }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).update(\n deepmerge(\n {\n where: filters,\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { where: any; data: any }\n );\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Parameters<ModelDelegate[\"updateMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to identify records to update.\n * @param {Parameters<ModelDelegate[\"updateMany\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to update the records with.\n * @param {TOptions} [queryOptions] - Additional query options.\n * @returns {Promise<ReturnType<ModelDelegate[\"updateMany\"]>>} The result of the updateMany operation.\n */\n async updateMany<\n TOptions extends Omit<\n Parameters<ModelDelegate[\"updateMany\"]>[0],\n \"where\" | \"data\"\n >,\n >(\n filters: Parameters<ModelDelegate[\"updateMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<ModelDelegate[\"updateMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"updateMany\"] extends (args: {\n where: any;\n data: any;\n }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (Array.isArray(data) && this.modelName === \"user\")\n await new Promise((resolve) => {\n (data as { [x: string]: any; password?: string }[]).forEach(\n async (curr, i) => {\n if (\"password\" in data[i])\n if (!authService.isPasswordHashed(curr.password!))\n (data[i] as any).password = await authService.hashPassword(\n curr.password!\n );\n\n if (i === data.length - 1) resolve(undefined);\n }\n );\n });\n\n const firstMerge = deepmerge({ data }, (queryOptions as {}) || {});\n\n return await (prisma[this.modelName] as ModelDelegate).updateMany(\n deepmerge({ where: filters }, firstMerge) as {\n where: any;\n data: any;\n }\n );\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Parameters<ModelDelegate[\"delete\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @returns {Promise<ReturnType<ModelDelegate[\"delete\"]>>} The deleted record or null if an error occurs.\n */\n async deleteOne(\n filters: Parameters<ModelDelegate[\"delete\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<ReturnType<ModelDelegate[\"delete\"]>> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).delete({\n where: filters,\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Parameters<ModelDelegate[\"deleteMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : Record<string, any>} filters - The filter to identify records to delete.\n * @returns {Promise<ReturnType<ModelDelegate[\"deleteMany\"]>>} The result of the deleteMany operation.\n */\n async deleteMany(\n filters: Parameters<ModelDelegate[\"deleteMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : Record<string, any>\n ): Promise<ReturnType<ModelDelegate[\"deleteMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).deleteMany({\n where: filters,\n });\n }\n}\n\n/**\n * Generates a set of base service instances for all available models.\n *\n * @returns {Record<string, BaseService>} A dictionary of base service instances, keyed by model name.\n */\nexport function getBaseServices(): Record<string, BaseService<any>> {\n const models = getModels();\n const baseServices: Record<string, BaseService<any>> = {};\n models.forEach((model) => {\n baseServices[`${camelCase(model)}`] = new BaseService(model);\n });\n return baseServices;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":"AAAA,OAAO,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C,EAAE,IAAI,EAAE,EAAG,YAAmB,IAAI,EAAE,CAAC,CAAC;QAEnE,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,UAAU,CAC/D,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,UAAU,CAGvC,CACF,CAAC;IACJ,CAAC;IAQD,KAAK,CAAC,SAAS,CACb,OAKO;QAEP,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAC;QAEnC,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,MAAM,CAAC;YAC5D,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC;IAQD,KAAK,CAAC,UAAU,CACd,OAKuB;QAEvB,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAC;QAEnC,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,UAAU,CAAC;YAChE,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC;CACF;AAOD,MAAM,UAAU,eAAe;IAC7B,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,YAAY,GAAqC,EAAE,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport {\n getModels,\n getPrismaModelRelations,\n RelationFields,\n} from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { handleRelationFieldsInBody } from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n *\n * by model-specific service classes.\n *\n * @class BaseService\n *\n * @usage\n *\n * **Example:** creating a simple service\n *\n * ```ts\n * import { prisma } from '../../utils/prisma'\n *\n * const userService = new BaseService<typeof prisma.user>(\"user\")\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-service-class}\n *\n */\nexport class BaseService<ModelDelegate extends Record<string, any> = any> {\n /**\n * The camelCase name of the model\n * @public\n */\n modelName: string;\n\n /**\n * Object containing singular and list relation fields for the model\n * @public\n */\n relationFields: RelationFields;\n\n /**\n * Instance of the Prisma client\n * @public\n */\n prisma: any;\n\n /**\n * Creates an instance of BaseService.\n * @param {string} modelName - The name of the model to perform operations on.\n */\n constructor(modelName: string) {\n this.modelName = camelCase(modelName);\n this.relationFields = getPrismaModelRelations(pascalCase(modelName))!;\n }\n\n /**\n * Creates a single record in the database.\n *\n * @param {Parameters<ModelDelegate[\"create\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to create the record with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"create\"]>>} The created record.\n */\n async createOne<\n TOptions extends Omit<Parameters<ModelDelegate[\"create\"]>[0], \"data\">,\n >(\n data: Parameters<ModelDelegate[\"create\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"create\"] extends (args: { data: any }) => infer R ? R : any\n > {\n // user uer Password123 true false Promise { true }\n if (kebabCase(this.modelName) === \"user\" && (data as any).password)\n if (!authService.isPasswordHashed((data as any).password))\n (data as any).password = await authService.hashPassword(\n (data as any).password\n );\n\n const prisma = getPrismaInstance();\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(\n data as Record<string, any>,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n return await (prisma[this.modelName] as ModelDelegate).create(\n deepmerge(\n {\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { data: any }\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Parameters<ModelDelegate[\"createMany\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - An array of data to create records with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"createMany\"]>>} The result of the createMany operation.\n */\n async createMany<\n TOptions extends Omit<Parameters<ModelDelegate[\"createMany\"]>[0], \"data\">,\n >(\n data: Parameters<ModelDelegate[\"createMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"createMany\"] extends (args: { data: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n const dataWithRelationFieldsHandled: any[] = [];\n\n if (Array.isArray(data))\n await new Promise((resolve) => {\n (data as { [x: string]: any; password?: string }[]).forEach(\n async (curr, i) => {\n if (\"password\" in curr && this.modelName === \"user\")\n if (!authService.isPasswordHashed(curr.password!))\n data[i].password = await authService.hashPassword(\n curr?.password!\n );\n\n dataWithRelationFieldsHandled[i] = handleRelationFieldsInBody(\n data[i] as Record<string, any>,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n if (i === data.length - 1) resolve(null);\n }\n );\n });\n\n return await (prisma[this.modelName] as ModelDelegate).createMany(\n deepmerge(\n { data: dataWithRelationFieldsHandled },\n (queryOptions as {}) || {}\n ) as {\n data: any;\n }\n );\n }\n\n /**\n * Counts records based on provided filters.\n *\n * @param {Parameters<ModelDelegate[\"count\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to apply to the query.\n * @returns {Promise<number>} The count of records matching the filters.\n */\n async count(\n filters: Parameters<ModelDelegate[\"count\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<number> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).count({\n where: filters,\n });\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Parameters<ModelDelegate[\"findMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to apply to the query.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findMany\"]>>} The found data.\n */\n async findMany<\n TOptions extends Omit<Parameters<ModelDelegate[\"findMany\"]>[0], \"where\">,\n >(\n filters?: Parameters<ModelDelegate[\"findMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findMany\"] extends (\n args: { where: any } & TOptions\n ) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).findMany(\n deepmerge({ where: filters }, (queryOptions as {}) || {}) as {\n where: any;\n } & TOptions\n );\n }\n\n /**\n * Finds a single record by its ID.\n *\n * @param {string | number} id - The ID of the record to find.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findUnique\"]>>} The found record or null if not found.\n */\n async findById<\n TOptions extends Omit<Parameters<ModelDelegate[\"findUnique\"]>[0], \"where\">,\n >(\n id: string | number,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findUnique\"] extends (args: { where: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).findUnique(\n deepmerge(\n {\n where: { id },\n },\n queryOptions || {}\n ) as { where: { id: string | number } }\n );\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Parameters<ModelDelegate[\"findFirst\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any | Parameters<TModel[\"findUnique\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findOne<\n TOptions extends\n | Omit<Parameters<ModelDelegate[\"findFirst\"]>[0], \"where\">\n | Omit<Parameters<ModelDelegate[\"findUnique\"]>[0], \"where\">,\n >(\n filters: Parameters<ModelDelegate[\"findFirst\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any | Parameters<ModelDelegate[\"findUnique\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findFirst\"] extends (args: { where: any }) => infer R\n ? R\n : ModelDelegate[\"findUnique\"] extends (args: { where: any }) => infer R2\n ? R2\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (\n Object.keys(filters as Record<string, any>).length === 1 &&\n \"id\" in (filters as Record<string, any>) &&\n (filters as any).id !== \"me\"\n )\n return (prisma[this.modelName] as ModelDelegate).findUnique(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).findFirst(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any }\n );\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Parameters<ModelDelegate[\"update\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {Parameters<ModelDelegate[\"update\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to update the record with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"update\"]>>} The updated record or null if not found.\n */\n async updateOne<\n TOptions extends Omit<\n Parameters<ModelDelegate[\"update\"]>[0],\n \"where\" | \"data\"\n >,\n >(\n filters: Parameters<ModelDelegate[\"update\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<ModelDelegate[\"update\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"update\"] extends (args: { where: any; data: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && (data as any)?.password) {\n if (!authService.isPasswordHashed((data as any).password!))\n (data as any).password = await authService.hashPassword(\n (data as any)?.password\n );\n }\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(\n data as Record<string, any>,\n {\n ...this.relationFields,\n }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).update(\n deepmerge(\n {\n where: filters,\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { where: any; data: any }\n );\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Parameters<ModelDelegate[\"updateMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to identify records to update.\n * @param {Parameters<ModelDelegate[\"updateMany\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to update the records with.\n * @param {TOptions} [queryOptions] - Additional query options.\n * @returns {Promise<ReturnType<ModelDelegate[\"updateMany\"]>>} The result of the updateMany operation.\n */\n async updateMany<\n TOptions extends Omit<\n Parameters<ModelDelegate[\"updateMany\"]>[0],\n \"where\" | \"data\"\n >,\n >(\n filters: Parameters<ModelDelegate[\"updateMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<ModelDelegate[\"updateMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"updateMany\"] extends (args: {\n where: any;\n data: any;\n }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (Array.isArray(data) && this.modelName === \"user\")\n await new Promise((resolve) => {\n (data as { [x: string]: any; password?: string }[]).forEach(\n async (curr, i) => {\n if (\"password\" in data[i])\n if (!authService.isPasswordHashed(curr.password!))\n (data[i] as any).password = await authService.hashPassword(\n curr.password!\n );\n\n if (i === data.length - 1) resolve(undefined);\n }\n );\n });\n\n const firstMerge = deepmerge({ data }, (queryOptions as {}) || {});\n\n return await (prisma[this.modelName] as ModelDelegate).updateMany(\n deepmerge({ where: filters }, firstMerge) as {\n where: any;\n data: any;\n }\n );\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Parameters<ModelDelegate[\"delete\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @returns {Promise<ReturnType<ModelDelegate[\"delete\"]>>} The deleted record or null if an error occurs.\n */\n async deleteOne(\n filters: Parameters<ModelDelegate[\"delete\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<ReturnType<ModelDelegate[\"delete\"]>> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).delete({\n where: filters,\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Parameters<ModelDelegate[\"deleteMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : Record<string, any>} filters - The filter to identify records to delete.\n * @returns {Promise<ReturnType<ModelDelegate[\"deleteMany\"]>>} The result of the deleteMany operation.\n */\n async deleteMany(\n filters: Parameters<ModelDelegate[\"deleteMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : Record<string, any>\n ): Promise<ReturnType<ModelDelegate[\"deleteMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).deleteMany({\n where: filters,\n });\n }\n}\n\n/**\n * Generates a set of base service instances for all available models.\n *\n * @returns {Record<string, BaseService>} A dictionary of base service instances, keyed by model name.\n */\nexport function getBaseServices(): Record<string, BaseService<any>> {\n const models = getModels();\n const baseServices: Record<string, BaseService<any>> = {};\n models.forEach((model) => {\n baseServices[`${camelCase(model)}`] = new BaseService(model);\n });\n return baseServices;\n}\n"]}
|
|
@@ -8,7 +8,7 @@ import catchAsync from "../../../error-handler/utils/catch-async.js";
|
|
|
8
8
|
export function setupRouters(models, router, arkosConfigs) {
|
|
9
9
|
return models.map(async (model) => {
|
|
10
10
|
const modelNameInKebab = kebabCase(model);
|
|
11
|
-
const modelModules = await importPrismaModelModules(modelNameInKebab);
|
|
11
|
+
const modelModules = await importPrismaModelModules(modelNameInKebab, arkosConfigs);
|
|
12
12
|
const { middlewares, authConfigs, prismaQueryOptions, router: customRouterModule, dtos, schemas, } = modelModules;
|
|
13
13
|
const routeName = pluralize.plural(modelNameInKebab);
|
|
14
14
|
const controller = new BaseController(model);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":"AACA,OAAO,SAAS,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAGtD,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,WAAW,MAAM,4BAA4B,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EACL,8BAA8B,EAC9B,4CAA4C,EAC5C,YAAY,GACb,MAAM,wBAAwB,CAAC;AAChC,OAAO,UAAU,MAAM,0CAA0C,CAAC;AAElE,MAAM,UAAU,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,wBAAwB,CAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,kBAA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IAEhB,IAAI,CAAC,YAAY,EAAE,MAAM;QAAE,OAAO,KAAK,CAAC;IAExC,MAAM,eAAe,GAAG,YAAY,CAAC,MAAM,CAAC,SAAS,CAAC;IACtD,IAAI,eAAe,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC;QAAE,OAAO,eAAe,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAE9E,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { Router } from \"express\";\nimport pluralize from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\nimport catchAsync from \"../../../error-handler/utils/catch-async\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = pluralize.plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n const routerConfig: RouterConfig = customRouterModule?.config || {};\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n (layer.path === `/api/${path}` ||\n layer.path === `api/${path}` ||\n layer.path === `api/${path}/` ||\n layer.path === `/api/${path}/`) &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !routerConfig?.disable)\n router.use(`/${routeName}`, customRouterModule.default);\n\n function safeCatchAsync(middleware: any) {\n return middleware ? catchAsync(middleware) : undefined;\n }\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(routerConfig, \"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeCreateOne) || controller.createOne,\n safeCatchAsync(middlewares?.beforeCreateOne)\n ? controller.createOne\n : safeCatchAsync(middlewares?.afterCreateOne) || sendResponse,\n safeCatchAsync(middlewares?.beforeCreateOne) &&\n safeCatchAsync(middlewares?.afterCreateOne)\n ? safeCatchAsync(middlewares?.afterCreateOne)\n : sendResponse,\n ].filter((m) => !!m),\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(routerConfig, \"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeFindMany) || controller.findMany,\n safeCatchAsync(middlewares?.beforeFindMany)\n ? controller.findMany\n : safeCatchAsync(middlewares?.afterFindMany) || sendResponse,\n safeCatchAsync(middlewares?.beforeFindMany) &&\n safeCatchAsync(middlewares?.afterFindMany)\n ? safeCatchAsync(middlewares?.afterFindMany)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(routerConfig, \"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeCreateMany) ||\n controller.createMany,\n safeCatchAsync(middlewares?.beforeCreateMany)\n ? controller.createMany\n : safeCatchAsync(middlewares?.afterCreateMany) || sendResponse,\n safeCatchAsync(middlewares?.beforeCreateMany) &&\n safeCatchAsync(middlewares?.afterCreateMany)\n ? safeCatchAsync(middlewares?.afterCreateMany)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(routerConfig, \"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdateMany) ||\n controller.updateMany,\n safeCatchAsync(middlewares?.beforeUpdateMany)\n ? controller.updateMany\n : safeCatchAsync(middlewares?.afterUpdateMany) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdateMany) &&\n safeCatchAsync(middlewares?.afterUpdateMany)\n ? safeCatchAsync(middlewares?.afterUpdateMany)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(routerConfig, \"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeDeleteMany) ||\n controller.deleteMany,\n safeCatchAsync(middlewares?.beforeDeleteMany)\n ? controller.deleteMany\n : safeCatchAsync(middlewares?.afterDeleteMany) || sendResponse,\n safeCatchAsync(middlewares?.beforeDeleteMany) &&\n safeCatchAsync(middlewares?.afterDeleteMany)\n ? safeCatchAsync(middlewares?.afterDeleteMany)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(routerConfig, \"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeFindOne) || controller.findOne,\n safeCatchAsync(middlewares?.beforeFindOne)\n ? controller.findOne\n : safeCatchAsync(middlewares?.afterFindOne) || sendResponse,\n safeCatchAsync(middlewares?.beforeFindOne) &&\n safeCatchAsync(middlewares?.afterFindOne)\n ? safeCatchAsync(middlewares?.afterFindOne)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(routerConfig, \"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdateOne) || controller.updateOne,\n safeCatchAsync(middlewares?.beforeUpdateOne)\n ? controller.updateOne\n : safeCatchAsync(middlewares?.afterUpdateOne) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdateOne) &&\n safeCatchAsync(middlewares?.afterUpdateOne)\n ? safeCatchAsync(middlewares?.afterUpdateOne)\n : sendResponse,\n ].filter((m) => !!m),\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(routerConfig, \"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeDeleteOne) || controller.deleteOne,\n safeCatchAsync(middlewares?.beforeDeleteOne)\n ? controller.deleteOne\n : safeCatchAsync(middlewares?.afterDeleteOne) || sendResponse,\n safeCatchAsync(middlewares?.beforeDeleteOne) &&\n safeCatchAsync(middlewares?.afterDeleteOne)\n ? safeCatchAsync(middlewares?.afterDeleteOne)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n });\n}\n\nexport function isEndpointDisabled(\n routerConfig: RouterConfig,\n endpoint: RouterEndpoint\n): boolean {\n if (!routerConfig?.disable) return false;\n\n if (routerConfig.disable === true) return true;\n\n if (typeof routerConfig.disable === \"object\")\n return routerConfig.disable[endpoint] === true;\n\n return false;\n}\n\nexport function isParentEndpointAllowed(\n routerConfig: any,\n endpoint: string\n): boolean {\n if (!routerConfig?.parent) return false;\n\n const parentEndpoints = routerConfig.parent.endpoints;\n if (parentEndpoints === \"*\") return true;\n if (Array.isArray(parentEndpoints)) return parentEndpoints.includes(endpoint);\n\n return true; // Default to allow if not specified\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":"AACA,OAAO,SAAS,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,SA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CAAC;oBACzC,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,cAAc,CAAC;oBAC7C,CAAC,CAAC,YAAY;gBAChB,YAAY;aACb,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CACrB,CAAC;QACJ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,YAA0B,EAC1B,QAAwB;IAExB,IAAI,CAAC,YAAY,EAAE,OAAO;QAAE,OAAO,KAAK,CAAC;IAEzC,IAAI,YAAY,CAAC,OAAO,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAE/C,IAAI,OAAO,YAAY,CAAC,OAAO,KAAK,QAAQ;QAC1C,OAAO,YAAY,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC;IAEjD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,YAAiB,EACjB,QAAgB;IAEhB,IAAI,CAAC,YAAY,EAAE,MAAM;QAAE,OAAO,KAAK,CAAC;IAExC,MAAM,eAAe,GAAG,YAAY,CAAC,MAAM,CAAC,SAAS,CAAC;IACtD,IAAI,eAAe,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC;QAAE,OAAO,eAAe,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAE9E,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { Router } from \"express\";\nimport pluralize from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\nimport catchAsync from \"../../../error-handler/utils/catch-async\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(\n modelNameInKebab,\n arkosConfigs\n );\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = pluralize.plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n const routerConfig: RouterConfig = customRouterModule?.config || {};\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n (layer.path === `/api/${path}` ||\n layer.path === `api/${path}` ||\n layer.path === `api/${path}/` ||\n layer.path === `/api/${path}/`) &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (key: string) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !routerConfig?.disable)\n router.use(`/${routeName}`, customRouterModule.default);\n\n function safeCatchAsync(middleware: any) {\n return middleware ? catchAsync(middleware) : undefined;\n }\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(routerConfig, \"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeCreateOne) || controller.createOne,\n safeCatchAsync(middlewares?.beforeCreateOne)\n ? controller.createOne\n : safeCatchAsync(middlewares?.afterCreateOne) || sendResponse,\n safeCatchAsync(middlewares?.beforeCreateOne) &&\n safeCatchAsync(middlewares?.afterCreateOne)\n ? safeCatchAsync(middlewares?.afterCreateOne)\n : sendResponse,\n ].filter((m) => !!m),\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(routerConfig, \"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeFindMany) || controller.findMany,\n safeCatchAsync(middlewares?.beforeFindMany)\n ? controller.findMany\n : safeCatchAsync(middlewares?.afterFindMany) || sendResponse,\n safeCatchAsync(middlewares?.beforeFindMany) &&\n safeCatchAsync(middlewares?.afterFindMany)\n ? safeCatchAsync(middlewares?.afterFindMany)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(routerConfig, \"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeCreateMany) ||\n controller.createMany,\n safeCatchAsync(middlewares?.beforeCreateMany)\n ? controller.createMany\n : safeCatchAsync(middlewares?.afterCreateMany) || sendResponse,\n safeCatchAsync(middlewares?.beforeCreateMany) &&\n safeCatchAsync(middlewares?.afterCreateMany)\n ? safeCatchAsync(middlewares?.afterCreateMany)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(routerConfig, \"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdateMany) ||\n controller.updateMany,\n safeCatchAsync(middlewares?.beforeUpdateMany)\n ? controller.updateMany\n : safeCatchAsync(middlewares?.afterUpdateMany) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdateMany) &&\n safeCatchAsync(middlewares?.afterUpdateMany)\n ? safeCatchAsync(middlewares?.afterUpdateMany)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(routerConfig, \"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeDeleteMany) ||\n controller.deleteMany,\n safeCatchAsync(middlewares?.beforeDeleteMany)\n ? controller.deleteMany\n : safeCatchAsync(middlewares?.afterDeleteMany) || sendResponse,\n safeCatchAsync(middlewares?.beforeDeleteMany) &&\n safeCatchAsync(middlewares?.afterDeleteMany)\n ? safeCatchAsync(middlewares?.afterDeleteMany)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(routerConfig, \"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeFindOne) || controller.findOne,\n safeCatchAsync(middlewares?.beforeFindOne)\n ? controller.findOne\n : safeCatchAsync(middlewares?.afterFindOne) || sendResponse,\n safeCatchAsync(middlewares?.beforeFindOne) &&\n safeCatchAsync(middlewares?.afterFindOne)\n ? safeCatchAsync(middlewares?.afterFindOne)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(routerConfig, \"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdateOne) || controller.updateOne,\n safeCatchAsync(middlewares?.beforeUpdateOne)\n ? controller.updateOne\n : safeCatchAsync(middlewares?.afterUpdateOne) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdateOne) &&\n safeCatchAsync(middlewares?.afterUpdateOne)\n ? safeCatchAsync(middlewares?.afterUpdateOne)\n : sendResponse,\n ].filter((m) => !!m),\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(routerConfig, \"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeDeleteOne) || controller.deleteOne,\n safeCatchAsync(middlewares?.beforeDeleteOne)\n ? controller.deleteOne\n : safeCatchAsync(middlewares?.afterDeleteOne) || sendResponse,\n safeCatchAsync(middlewares?.beforeDeleteOne) &&\n safeCatchAsync(middlewares?.afterDeleteOne)\n ? safeCatchAsync(middlewares?.afterDeleteOne)\n : sendResponse,\n sendResponse,\n ].filter((m) => !!m)\n );\n }\n });\n}\n\nexport function isEndpointDisabled(\n routerConfig: RouterConfig,\n endpoint: RouterEndpoint\n): boolean {\n if (!routerConfig?.disable) return false;\n\n if (routerConfig.disable === true) return true;\n\n if (typeof routerConfig.disable === \"object\")\n return routerConfig.disable[endpoint] === true;\n\n return false;\n}\n\nexport function isParentEndpointAllowed(\n routerConfig: any,\n endpoint: string\n): boolean {\n if (!routerConfig?.parent) return false;\n\n const parentEndpoints = routerConfig.parent.endpoints;\n if (parentEndpoints === \"*\") return true;\n if (Array.isArray(parentEndpoints)) return parentEndpoints.includes(endpoint);\n\n return true; // Default to allow if not specified\n}\n"]}
|
|
@@ -34,6 +34,8 @@ export default function errorHandler(err, req, res, next) {
|
|
|
34
34
|
error = errorControllerHelper.handleForeignKeyConstraintError(err);
|
|
35
35
|
if (err.code === "P2004")
|
|
36
36
|
error = errorControllerHelper.handleConstraintFailedError(err);
|
|
37
|
+
if (err.code === "P2025")
|
|
38
|
+
error = errorControllerHelper.handleNonExistingRecord(err);
|
|
37
39
|
if (err.code === "P3000")
|
|
38
40
|
error = errorControllerHelper.handleSchemaCreationFailedError(err);
|
|
39
41
|
if (err.code === "P3001")
|
|
@@ -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;IAElB,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU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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;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n next: NextFunction\n): void {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n if (!error.isOperational) error = new AppError(\"Something went wrong!\", 500);\n\n // Send the error response for production environment\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.controller.js","sour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M;gBAClB,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE;gBACpB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,SAAS;aAC5B,CAAC,CAAC;;YAEH,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACnB,MAAM,EAAE,OAAO;gBACf,OAAO,EAAE,uBAAuB;aACjC,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;SACrB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,yBAAyB;KACnC,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n next: NextFunction\n): void {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n if (!error.isOperational) error = new AppError(\"Something went wrong!\", 500);\n\n // Send the error response for production environment\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catch-async.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/catch-async.ts"],"names":[],"mappings":"AAwBA,MAAM,UAAU,GACd,CAAC,EAAuB,EAAE,EAAE,CAC5B,KAAK,
|
|
1
|
+
{"version":3,"file":"catch-async.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/catch-async.ts"],"names":[],"mappings":"AAwBA,MAAM,UAAU,GACd,CAAC,EAAuB,EAAE,EAAE,CAC5B,KAAK,EACH,GAAiB,EACjB,GAAkB,EAClB,IAAuB,EACR,EAAE;IACjB,IAAI,CAAC;QACH,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAS,CAAC;IAC5C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,GAAG,CAAC,CAAC;IACZ,CAAC;AACH,CAAC,CAAC;AAEJ,eAAe,UAAU,CAAC","sourcesContent":["import {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../../types\";\n\n/**\n * Used to wrap request handlers and middleware for automatic catch async errors and throw to next to invoke the global error handler\n *\n * @param {ArkosRequestHandler} fn - an express request handler or middleware that will be called with req, res, next, with catch attached for error handling\n * @returns\n *\n * @example\n * ```typescript\n * import { ArkosRequest, ArkosResponse, ArkosNextFunction } from 'arkos'\n *\n * export const getManyPosts = catchAsync(async\n * (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n * const posts = await getSomePosts()\n * res.status(200).json({ data: posts })\n * })\n * ```\n */\nconst catchAsync =\n (fn: ArkosRequestHandler) =>\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ): Promise<void> => {\n try {\n return (await fn(req, res, next)) as void;\n } catch (err) {\n next(err);\n }\n };\n\nexport default catchAsync;\n"]}
|
|
@@ -152,4 +152,9 @@ export function handleEmptyResultError(err) {
|
|
|
152
152
|
const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;
|
|
153
153
|
return new AppError(message, 404);
|
|
154
154
|
}
|
|
155
|
+
export function handleNonExistingRecord(err) {
|
|
156
|
+
const message = err?.meta?.cause ||
|
|
157
|
+
`Operation could not be completed as the required record was not found`;
|
|
158
|
+
return new AppError(message, 404, err.meta || {}, "PrismaRecordNotFound");
|
|
159
|
+
}
|
|
155
160
|
//# sourceMappingURL=error-handler.helpers.js.map
|