arkos 1.1.96-test → 1.1.98-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.controller.js +0 -5
- package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
- package/dist/cjs/modules/auth/auth.router.js +82 -35
- package/dist/cjs/modules/auth/auth.router.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +5 -5
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +7 -14
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/base.service.js +21 -12
- package/dist/cjs/modules/base/base.service.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.middlewares.helpers.js +50 -0
- package/dist/cjs/modules/base/utils/helpers/base.middlewares.helpers.js.map +1 -0
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +93 -40
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/cjs/server.js +3 -2
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +176 -26
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/index.js +3 -2
- package/dist/cjs/utils/cli/index.js.map +1 -1
- package/dist/cjs/utils/cli/start.js +12 -8
- package/dist/cjs/utils/cli/start.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +7 -0
- package/dist/cjs/utils/cli/utils/cli.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/fs.helpers.js +1 -1
- package/dist/cjs/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +7 -0
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/es2020/modules/auth/auth.controller.js +0 -5
- package/dist/es2020/modules/auth/auth.controller.js.map +1 -1
- package/dist/es2020/modules/auth/auth.router.js +82 -35
- package/dist/es2020/modules/auth/auth.router.js.map +1 -1
- package/dist/es2020/modules/auth/auth.service.js +5 -5
- package/dist/es2020/modules/auth/auth.service.js.map +1 -1
- package/dist/es2020/modules/base/base.middlewares.js +7 -14
- package/dist/es2020/modules/base/base.middlewares.js.map +1 -1
- package/dist/es2020/modules/base/base.service.js +21 -12
- package/dist/es2020/modules/base/base.service.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.middlewares.helpers.js +44 -0
- package/dist/es2020/modules/base/utils/helpers/base.middlewares.helpers.js.map +1 -0
- package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js +93 -40
- package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/es2020/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/es2020/server.js +3 -2
- package/dist/es2020/server.js.map +1 -1
- package/dist/es2020/types/index.js.map +1 -1
- package/dist/es2020/utils/cli/dev.js +173 -27
- package/dist/es2020/utils/cli/dev.js.map +1 -1
- package/dist/es2020/utils/cli/index.js +3 -2
- package/dist/es2020/utils/cli/index.js.map +1 -1
- package/dist/es2020/utils/cli/start.js +11 -8
- package/dist/es2020/utils/cli/start.js.map +1 -1
- package/dist/es2020/utils/cli/utils/cli.helpers.js +6 -0
- package/dist/es2020/utils/cli/utils/cli.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/fs.helpers.js +1 -1
- package/dist/es2020/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/es2020/utils/helpers/models.helpers.js +7 -0
- package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
- package/dist/types/modules/base/base.middlewares.d.ts +2 -2
- package/dist/types/modules/base/base.service.d.ts +2 -2
- package/dist/types/modules/base/utils/helpers/base.middlewares.helpers.d.ts +3 -0
- package/dist/types/server.d.ts +1 -0
- package/dist/types/types/index.d.ts +11 -3
- package/dist/types/utils/cli/dev.d.ts +1 -0
- package/dist/types/utils/cli/start.d.ts +1 -0
- package/dist/types/utils/cli/utils/cli.helpers.d.ts +1 -0
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":";;;;;;AAidA,0CAOC;AAxdD,iFAIiD;AACjD,uEAI4C;AAC5C,4FAA6D;AAC7D,+EAAkF;AAClF,uEAAuE;AACvE,wEAA+C;AAuB/C,MAAa,WAAW;IAuBtB,YAAY,SAAiB;QAC3B,IAAI,CAAC,SAAS,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,cAAc,GAAG,IAAA,wCAAuB,EAAC,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAE,CAAC;IACxE,CAAC;IASD,KAAK,CAAC,SAAS,CAGb,IAKO,EACP,YAAuB;QAKvB,IAAI,IAAA,+BAAS,EAAC,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAK,IAAY,CAAC,QAAQ;YAChE,IAAI,CAAC,sBAAW,CAAC,gBAAgB,CAAE,IAAY,CAAC,QAAQ,CAAC;gBACtD,IAAY,CAAC,QAAQ,GAAG,MAAM,sBAAW,CAAC,YAAY,CACpD,IAAY,CAAC,QAAQ,CACvB,CAAC;QAEN,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;QAEnC,MAAM,6BAA6B,GAAG,IAAA,iDAA0B,EAC9D,IAA2B,EAC3B;YACE,GAAG,IAAI,CAAC,cAAc;SACvB,EACD,CAAC,QAAQ,EAAE,YAAY,EAAE,QAAQ,CAAC,CACnC,CAAC;QAEF,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,MAAM,CAC3D,IAAA,0BAAS,EACP;YACE,IAAI,EAAE,6BAA6B;SACpC,EACA,YAAmB,IAAI,EAAE,CACV,CACnB,CAAC;IACJ,CAAC;IASD,KA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OAKO;QAEP,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,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,IAAA,kCAAiB,GAAE,CAAC;QAEnC,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,UAAU,CAAC;YAChE,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC;CACF;AAtaD,kCAsaC;AAOD,SAAgB,eAAe;IAC7B,MAAM,MAAM,GAAG,IAAA,0BAAS,GAAE,CAAC;IAC3B,MAAM,YAAY,GAAqC,EAAE,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,IAAA,+BAAS,EAAC,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\n if (Array.isArray(data))\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 curr.password = await authService.hashPassword(curr?.password!);\n\n data[i] = handleRelationFieldsInBody(\n data[i] as Record<string, any>,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).createMany(\n deepmerge({ data }, (queryOptions as {}) || {}) 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 Awaited<\n ReturnType<\n ModelDelegate[\"findMany\"] extends (\n args: { where: any } & TOptions\n ) => any\n ? ModelDelegate[\"findMany\"]\n : never\n >\n >\n > {\n const prisma = getPrismaInstance();\n return await (prisma[this.modelName] as ModelDelegate).findMany(\n deepmerge({ where: filters }, queryOptions || {})\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 (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 );\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":";;;;;;AA8dA,0CAOC;AAreD,iFAIiD;AACjD,uEAI4C;AAC5C,4FAA6D;AAC7D,+EAAkF;AAClF,uEAAuE;AACvE,wEAA+C;AAuB/C,MAAa,WAAW;IAuBtB,YAAY,SAAiB;QAC3B,IAAI,CAAC,SAAS,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,cAAc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,GAAG,IAAA,kCAAiB,GAAE,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,IAAA,kCAAiB,GAAE,CAAC;QAEnC,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,UAAU,CAAC;YAChE,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC;CACF;AAnbD,kCAmbC;AAOD,SAAgB,eAAe;IAC7B,MAAM,MAAM,GAAG,IAAA,0BAAS,GAAE,CAAC;IAC3B,MAAM,YAAY,GAAqC,EAAE,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,IAAA,+BAAS,EAAC,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"]}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.resolvePrismaQueryOptions = resolvePrismaQueryOptions;
|
|
7
|
+
const deepmerge_helper_1 = __importDefault(require("../../../../utils/helpers/deepmerge.helper"));
|
|
8
|
+
function resolvePrismaQueryOptions(prismaQueryOptions, action) {
|
|
9
|
+
if (!prismaQueryOptions) {
|
|
10
|
+
return {};
|
|
11
|
+
}
|
|
12
|
+
const options = prismaQueryOptions;
|
|
13
|
+
const actionOptions = options[action] || {};
|
|
14
|
+
let mergedOptions = options.queryOptions || {};
|
|
15
|
+
if (options.global) {
|
|
16
|
+
mergedOptions = (0, deepmerge_helper_1.default)(mergedOptions, options.global);
|
|
17
|
+
}
|
|
18
|
+
const generalOptions = getGeneralOptionsForAction(options, action);
|
|
19
|
+
if (generalOptions) {
|
|
20
|
+
mergedOptions = (0, deepmerge_helper_1.default)(mergedOptions, generalOptions);
|
|
21
|
+
}
|
|
22
|
+
if (actionOptions) {
|
|
23
|
+
mergedOptions = (0, deepmerge_helper_1.default)(mergedOptions, actionOptions);
|
|
24
|
+
}
|
|
25
|
+
return mergedOptions;
|
|
26
|
+
}
|
|
27
|
+
function getGeneralOptionsForAction(options, action) {
|
|
28
|
+
const actionMappings = {
|
|
29
|
+
findMany: ["find"],
|
|
30
|
+
findOne: ["find"],
|
|
31
|
+
create: ["create", "save"],
|
|
32
|
+
createOne: ["create", "save", "saveOne"],
|
|
33
|
+
createMany: ["create", "save", "saveMany"],
|
|
34
|
+
update: ["update", "save"],
|
|
35
|
+
updateOne: ["update", "save", "saveOne"],
|
|
36
|
+
updateMany: ["update", "save", "saveMany"],
|
|
37
|
+
delete: ["delete"],
|
|
38
|
+
deleteOne: ["delete"],
|
|
39
|
+
deleteMany: ["delete"],
|
|
40
|
+
};
|
|
41
|
+
const generalKeys = actionMappings[action] || [];
|
|
42
|
+
let generalOptions = {};
|
|
43
|
+
for (const key of generalKeys) {
|
|
44
|
+
if (options[key]) {
|
|
45
|
+
generalOptions = (0, deepmerge_helper_1.default)(generalOptions, options[key]);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return Object.keys(generalOptions).length > 0 ? generalOptions : null;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=base.middlewares.helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"base.middlewares.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.middlewares.helpers.ts"],"names":[],"mappings":";;;;;AAYA,8DA+BC;AA1CD,kGAAmE;AAWnE,SAAgB,yBAAyB,CACvC,kBAAqE,EACrE,MAAyB;IAEzB,IAAI,CAAC,kBAAkB,EAAE,CAAC;QACxB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,OAAO,GAAG,kBAAyB,CAAC;IAC1C,MAAM,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IAG5C,IAAI,aAAa,GAAG,OAAO,CAAC,YAAY,IAAI,EAAE,CAAC;IAG/C,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;QACnB,aAAa,GAAG,IAAA,0BAAS,EAAC,aAAa,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3D,CAAC;IAGD,MAAM,cAAc,GAAG,0BAA0B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IACnE,IAAI,cAAc,EAAE,CAAC;QACnB,aAAa,GAAG,IAAA,0BAAS,EAAC,aAAa,EAAE,cAAc,CAAC,CAAC;IAC3D,CAAC;IAGD,IAAI,aAAa,EAAE,CAAC;QAClB,aAAa,GAAG,IAAA,0BAAS,EAAC,aAAa,EAAE,aAAa,CAAC,CAAC;IAC1D,CAAC;IAED,OAAO,aAAa,CAAC;AACvB,CAAC;AASD,SAAS,0BAA0B,CACjC,OAAY,EACZ,MAAyB;IAGzB,MAAM,cAAc,GAA6B;QAE/C,QAAQ,EAAE,CAAC,MAAM,CAAC;QAClB,OAAO,EAAE,CAAC,MAAM,CAAC;QAGjB,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,SAAS,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAC;QACxC,UAAU,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAC;QAG1C,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,SAAS,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAC;QACxC,UAAU,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAC;QAG1C,MAAM,EAAE,CAAC,QAAQ,CAAC;QAClB,SAAS,EAAE,CAAC,QAAQ,CAAC;QACrB,UAAU,EAAE,CAAC,QAAQ,CAAC;KACvB,CAAC;IAEF,MAAM,WAAW,GAAG,cAAc,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IACjD,IAAI,cAAc,GAAG,EAAE,CAAC;IAGxB,KAAK,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC;QAC9B,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACjB,cAAc,GAAG,IAAA,0BAAS,EAAC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC;AACxE,CAAC","sourcesContent":["import { AuthPrismaQueryOptions, PrismaQueryOptions } from \"../../../../types\";\nimport deepmerge from \"../../../../utils/helpers/deepmerge.helper\";\nimport { ControllerActions } from \"../../base.middlewares\";\n\n/**\n * Helper function to resolve and merge Prisma query options based on action and general options\n *\n * @template T - The type of the Prisma model\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options\n * @param {ControllerActions} action - The controller action to apply\n * @returns {Record<string, any>} The merged query options for the specific action\n */\nexport function resolvePrismaQueryOptions<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n): Record<string, any> {\n if (!prismaQueryOptions) {\n return {};\n }\n\n const options = prismaQueryOptions as any;\n const actionOptions = options[action] || {};\n\n // Start with deprecated queryOptions (for backward compatibility)\n let mergedOptions = options.queryOptions || {};\n\n // Apply global options (replaces queryOptions)\n if (options.global) {\n mergedOptions = deepmerge(mergedOptions, options.global);\n }\n\n // Apply general operation options based on action type\n const generalOptions = getGeneralOptionsForAction(options, action);\n if (generalOptions) {\n mergedOptions = deepmerge(mergedOptions, generalOptions);\n }\n\n // Finally apply specific action options (highest priority)\n if (actionOptions) {\n mergedOptions = deepmerge(mergedOptions, actionOptions);\n }\n\n return mergedOptions;\n}\n\n/**\n * Helper function to get general options based on the action type\n *\n * @param {any} options - The Prisma query options object\n * @param {ControllerActions} action - The controller action\n * @returns {Record<string, any> | null} The general options for the action type\n */\nfunction getGeneralOptionsForAction(\n options: any,\n action: ControllerActions\n): Record<string, any> | null {\n // Map actions to their general option categories\n const actionMappings: Record<string, string[]> = {\n // Find operations\n findMany: [\"find\"],\n findOne: [\"find\"],\n\n // Create operations\n create: [\"create\", \"save\"],\n createOne: [\"create\", \"save\", \"saveOne\"],\n createMany: [\"create\", \"save\", \"saveMany\"],\n\n // Update operations\n update: [\"update\", \"save\"],\n updateOne: [\"update\", \"save\", \"saveOne\"],\n updateMany: [\"update\", \"save\", \"saveMany\"],\n\n // Delete operations\n delete: [\"delete\"],\n deleteOne: [\"delete\"],\n deleteMany: [\"delete\"],\n };\n\n const generalKeys = actionMappings[action] || [];\n let generalOptions = {};\n\n // Merge all applicable general options in order of precedence\n for (const key of generalKeys) {\n if (options[key]) {\n generalOptions = deepmerge(generalOptions, options[key]);\n }\n }\n\n return Object.keys(generalOptions).length > 0 ? generalOptions : null;\n}\n"]}
|
|
@@ -10,6 +10,7 @@ const models_helpers_1 = require("../../../../utils/helpers/models.helpers");
|
|
|
10
10
|
const auth_service_1 = __importDefault(require("../../../auth/auth.service"));
|
|
11
11
|
const base_controller_1 = require("../../base.controller");
|
|
12
12
|
const base_middlewares_1 = require("../../base.middlewares");
|
|
13
|
+
const catch_async_1 = __importDefault(require("../../../error-handler/utils/catch-async"));
|
|
13
14
|
function setupRouters(models, router, arkosConfigs) {
|
|
14
15
|
return models.map(async (model) => {
|
|
15
16
|
const modelNameInKebab = (0, utils_1.kebabCase)(model);
|
|
@@ -45,69 +46,121 @@ function setupRouters(models, router, arkosConfigs) {
|
|
|
45
46
|
};
|
|
46
47
|
if (customRouterModule?.default && !customRouterModule?.config?.disable)
|
|
47
48
|
router.use(`/${routeName}`, customRouterModule.default);
|
|
49
|
+
function safeCatchAsync(middleware) {
|
|
50
|
+
return middleware ? (0, catch_async_1.default)(middleware) : undefined;
|
|
51
|
+
}
|
|
48
52
|
if (!isEndpointDisabled("createOne") &&
|
|
49
53
|
!hasCustomImplementation(`/${routeName}`, "post")) {
|
|
50
|
-
router.post(`/${routeName}`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Create", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("create")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "createOne"),
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
54
|
+
router.post(`/${routeName}`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Create", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("create")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "createOne"), ...[
|
|
55
|
+
safeCatchAsync(middlewares?.beforeCreateOne) || controller.createOne,
|
|
56
|
+
safeCatchAsync(middlewares?.beforeCreateOne)
|
|
57
|
+
? controller.createOne
|
|
58
|
+
: safeCatchAsync(middlewares?.afterCreateOne) || base_middlewares_1.sendResponse,
|
|
59
|
+
safeCatchAsync(middlewares?.beforeCreateOne) &&
|
|
60
|
+
safeCatchAsync(middlewares?.afterCreateOne)
|
|
61
|
+
? safeCatchAsync(middlewares?.afterCreateOne)
|
|
62
|
+
: base_middlewares_1.sendResponse,
|
|
63
|
+
].filter((m) => !!m), base_middlewares_1.sendResponse);
|
|
55
64
|
}
|
|
56
65
|
if (!isEndpointDisabled("findMany") &&
|
|
57
66
|
!hasCustomImplementation(`/${routeName}`, "get")) {
|
|
58
|
-
router.get(`/${routeName}`, auth_service_1.default.handleAuthenticationControl("View", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("View", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "findMany"),
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
67
|
+
router.get(`/${routeName}`, auth_service_1.default.handleAuthenticationControl("View", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("View", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "findMany"), ...[
|
|
68
|
+
safeCatchAsync(middlewares?.beforeFindMany) || controller.findMany,
|
|
69
|
+
safeCatchAsync(middlewares?.beforeFindMany)
|
|
70
|
+
? controller.findMany
|
|
71
|
+
: safeCatchAsync(middlewares?.afterFindMany) || base_middlewares_1.sendResponse,
|
|
72
|
+
safeCatchAsync(middlewares?.beforeFindMany) &&
|
|
73
|
+
safeCatchAsync(middlewares?.afterFindMany)
|
|
74
|
+
? safeCatchAsync(middlewares?.afterFindMany)
|
|
75
|
+
: base_middlewares_1.sendResponse,
|
|
76
|
+
base_middlewares_1.sendResponse,
|
|
77
|
+
].filter((m) => !!m));
|
|
63
78
|
}
|
|
64
79
|
if (!isEndpointDisabled("createMany") &&
|
|
65
80
|
!hasCustomImplementation(`/${routeName}/many`, "post")) {
|
|
66
|
-
router.post(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Create", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("createMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "createMany"),
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
81
|
+
router.post(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Create", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("createMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "createMany"), ...[
|
|
82
|
+
safeCatchAsync(middlewares?.beforeCreateMany) ||
|
|
83
|
+
controller.createMany,
|
|
84
|
+
safeCatchAsync(middlewares?.beforeCreateMany)
|
|
85
|
+
? controller.createMany
|
|
86
|
+
: safeCatchAsync(middlewares?.afterCreateMany) || base_middlewares_1.sendResponse,
|
|
87
|
+
safeCatchAsync(middlewares?.beforeCreateMany) &&
|
|
88
|
+
safeCatchAsync(middlewares?.afterCreateMany)
|
|
89
|
+
? safeCatchAsync(middlewares?.afterCreateMany)
|
|
90
|
+
: base_middlewares_1.sendResponse,
|
|
91
|
+
base_middlewares_1.sendResponse,
|
|
92
|
+
].filter((m) => !!m));
|
|
71
93
|
}
|
|
72
94
|
if (!isEndpointDisabled("updateMany") &&
|
|
73
95
|
!hasCustomImplementation(`/${routeName}/many`, "patch")) {
|
|
74
|
-
router.patch(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Update", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("updateMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "updateMany"),
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
96
|
+
router.patch(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Update", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("updateMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "updateMany"), ...[
|
|
97
|
+
safeCatchAsync(middlewares?.beforeUpdateMany) ||
|
|
98
|
+
controller.updateMany,
|
|
99
|
+
safeCatchAsync(middlewares?.beforeUpdateMany)
|
|
100
|
+
? controller.updateMany
|
|
101
|
+
: safeCatchAsync(middlewares?.afterUpdateMany) || base_middlewares_1.sendResponse,
|
|
102
|
+
safeCatchAsync(middlewares?.beforeUpdateMany) &&
|
|
103
|
+
safeCatchAsync(middlewares?.afterUpdateMany)
|
|
104
|
+
? safeCatchAsync(middlewares?.afterUpdateMany)
|
|
105
|
+
: base_middlewares_1.sendResponse,
|
|
106
|
+
base_middlewares_1.sendResponse,
|
|
107
|
+
].filter((m) => !!m));
|
|
79
108
|
}
|
|
80
109
|
if (!isEndpointDisabled("deleteMany") &&
|
|
81
110
|
!hasCustomImplementation(`/${routeName}/many`, "delete")) {
|
|
82
|
-
router.delete(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Delete", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("deleteMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "deleteMany"),
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
111
|
+
router.delete(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Delete", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("deleteMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "deleteMany"), ...[
|
|
112
|
+
safeCatchAsync(middlewares?.beforeDeleteMany) ||
|
|
113
|
+
controller.deleteMany,
|
|
114
|
+
safeCatchAsync(middlewares?.beforeDeleteMany)
|
|
115
|
+
? controller.deleteMany
|
|
116
|
+
: safeCatchAsync(middlewares?.afterDeleteMany) || base_middlewares_1.sendResponse,
|
|
117
|
+
safeCatchAsync(middlewares?.beforeDeleteMany) &&
|
|
118
|
+
safeCatchAsync(middlewares?.afterDeleteMany)
|
|
119
|
+
? safeCatchAsync(middlewares?.afterDeleteMany)
|
|
120
|
+
: base_middlewares_1.sendResponse,
|
|
121
|
+
base_middlewares_1.sendResponse,
|
|
122
|
+
].filter((middleware) => !!middleware));
|
|
87
123
|
}
|
|
88
124
|
if (!isEndpointDisabled("findOne") &&
|
|
89
125
|
!hasCustomImplementation(`/${routeName}/:id`, "get")) {
|
|
90
|
-
router.get(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("View", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("View", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("findOne")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "findOne"),
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
126
|
+
router.get(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("View", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("View", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("findOne")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "findOne"), ...[
|
|
127
|
+
safeCatchAsync(middlewares?.beforeFindOne) || controller.findOne,
|
|
128
|
+
safeCatchAsync(middlewares?.beforeFindOne)
|
|
129
|
+
? controller.findOne
|
|
130
|
+
: safeCatchAsync(middlewares?.afterFindOne) || base_middlewares_1.sendResponse,
|
|
131
|
+
safeCatchAsync(middlewares?.beforeFindOne) &&
|
|
132
|
+
safeCatchAsync(middlewares?.afterFindOne)
|
|
133
|
+
? safeCatchAsync(middlewares?.afterFindOne)
|
|
134
|
+
: base_middlewares_1.sendResponse,
|
|
135
|
+
base_middlewares_1.sendResponse,
|
|
136
|
+
].filter((m) => !!m));
|
|
95
137
|
}
|
|
96
138
|
if (!isEndpointDisabled("updateOne") &&
|
|
97
139
|
!hasCustomImplementation(`/${routeName}/:id`, "patch")) {
|
|
98
|
-
router.patch(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Update", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("update")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "updateOne"),
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
140
|
+
router.patch(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Update", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("update")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "updateOne"), ...[
|
|
141
|
+
safeCatchAsync(middlewares?.beforeUpdateOne) || controller.updateOne,
|
|
142
|
+
safeCatchAsync(middlewares?.beforeUpdateOne)
|
|
143
|
+
? controller.updateOne
|
|
144
|
+
: safeCatchAsync(middlewares?.afterUpdateOne) || base_middlewares_1.sendResponse,
|
|
145
|
+
safeCatchAsync(middlewares?.beforeUpdateOne) &&
|
|
146
|
+
safeCatchAsync(middlewares?.afterUpdateOne)
|
|
147
|
+
? safeCatchAsync(middlewares?.afterUpdateOne)
|
|
148
|
+
: base_middlewares_1.sendResponse,
|
|
149
|
+
].filter((m) => !!m), base_middlewares_1.sendResponse);
|
|
103
150
|
}
|
|
104
151
|
if (!isEndpointDisabled("deleteOne") &&
|
|
105
152
|
!hasCustomImplementation(`/${routeName}/:id`, "delete")) {
|
|
106
|
-
router.delete(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Delete", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("delete")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "deleteOne"),
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
153
|
+
router.delete(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Delete", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("delete")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "deleteOne"), ...[
|
|
154
|
+
safeCatchAsync(middlewares?.beforeDeleteOne) || controller.deleteOne,
|
|
155
|
+
safeCatchAsync(middlewares?.beforeDeleteOne)
|
|
156
|
+
? controller.deleteOne
|
|
157
|
+
: safeCatchAsync(middlewares?.afterDeleteOne) || base_middlewares_1.sendResponse,
|
|
158
|
+
safeCatchAsync(middlewares?.beforeDeleteOne) &&
|
|
159
|
+
safeCatchAsync(middlewares?.afterDeleteOne)
|
|
160
|
+
? safeCatchAsync(middlewares?.afterDeleteOne)
|
|
161
|
+
: base_middlewares_1.sendResponse,
|
|
162
|
+
base_middlewares_1.sendResponse,
|
|
163
|
+
].filter((m) => !!m));
|
|
111
164
|
}
|
|
112
165
|
});
|
|
113
166
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;AAeA,oCA0UC;AAxVD,yCAA6C;AAE7C,qDAAsD;AAGtD,6EAAoF;AACpF,8EAAqD;AACrD,2DAAuD;AACvD,6DAIgC;AAEhC,SAAgB,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,IAAA,iBAAS,EAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,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,EACnB,sBAAW,CAAC,2BAA2B,CACrC,QAAQ,EACR,WAAW,EAAE,qBAAqB,CACnC,EACD,sBAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,IAAA,iBAAS,EAAC,IAAA,oBAAQ,EAAC,gBAAgB,CAAC,CAAC,EACrC,WAAW,EAAE,aAAa,IAAI,EAAE,CACjC,EACD,IAAA,+DAA4C,EAC1C,wBAAwB,CAAC,QAAQ,CAAC,CACnC,EACD,IAAA,iDAA8B,EAC5B,kBAA6C,EAC7C,WAAW,CACZ,EACD,WAAW,EAAE,eAAe,IAAI,UAAU,CAAC,SAAS,EACpD,WAAW,EAAE,eAAe;gBAC1B,CAAC,CAAC,UAAU,CAAC,SAAS;gBACtB,CAAC,CAAC,WAAW,EAAE,cAAc,IAAI,+BAAY,EAC/C,WAAW,EAAE,eAAe,IAAI,WAAW,EAAE,cAAc;gBACzD,CAAC,CAAC,WAAW,EAAE,cAAc;gBAC7B,CAAC,CAAC,+BAAY,EAChB,+BAAY,CACb,CAAC;QACJ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } 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\";\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 = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default 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 determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\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 && !customRouterModule?.config?.disable)\n router.use(`/${routeName}`, customRouterModule.default);\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"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(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"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(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"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(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"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(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"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(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"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(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"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(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"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(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;AAgBA,oCAyWC;AAxXD,yCAA6C;AAE7C,qDAAsD;AAGtD,6EAAoF;AACpF,8EAAqD;AACrD,2DAAuD;AACvD,6DAIgC;AAChC,2FAAkE;AAElE,SAAgB,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,IAAA,iBAAS,EAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,IAAI,EACJ,OAAO,GACR,GAAG,YAAY,CAAC;QAEjB,MAAM,SAAS,GAAG,IAAA,kBAAM,EAAC,gBAAgB,CAAC,CAAC;QAC3C,MAAM,UAAU,GAAG,IAAI,gCAAc,CAAC,KAAK,CAAC,CAAC;QAG7C,MAAM,YAAY,GAAiB,kBAAkB,EAAE,MAAM,CAAC;QAC9D,MAAM,aAAa,GAAG,YAAY,EAAE,OAAO,IAAI,EAAE,CAAC;QAClD,MAAM,oBAAoB,GAAG,aAAa,KAAK,IAAI,CAAC;QAGpD,MAAM,YAAY,GAAI,kBAAkB,EAAE,OAAkB,IAAI,EAAE,CAAC;QACnE,MAA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BAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,IAAA,iBAAS,EAAC,IAAA,oBAAQ,EAAC,gBAAgB,CAAC,CAAC,EACrC,WAAW,EAAE,aAAa,IAAI,EAAE,CACjC,EACD,IAAA,+DAA4C,EAC1C,wBAAwB,CAAC,QAAQ,CAAC,CACnC,EACD,IAAA,iDAA8B,EAC5B,kBAA6C,EAC7C,WAAW,CACZ,EACD,GAAG;gBACD,cAAc,CAAC,WAAW,EAAE,eAAe,CAAC,IAAI,UAAU,CAAC,SAAS;gBACpE,cAAc,CAAC,WAAW,EAAE,eAAe,CAAC;oBAC1C,CAAC,CAAC,UAAU,CAAC,SAAS;oBACtB,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,cAAc,CAAC,IAAI,+BAAY;gBAC/D,cAAc,CAAC,WAAW,EAAE,eAAe,CAAC;oBAC5C,cAAc,CAAC,WAAW,EAAE,cAAc,CAAC;oBACzC,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,cAAc,CAAC;oBAC7C,CAAC,CAAC,+BAAY;gBAChB,+BAAY;aACb,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CACrB,CAAC;QACJ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } 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 = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default 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 determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\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 && !customRouterModule?.config?.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(\"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(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(\"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(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(\"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(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(\"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(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(\"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(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(\"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(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(\"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(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(\"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(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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AA2BA,wCAEC;AAED,4CAEC;AAED,8EAGC;AAED,8DAIC;AAED,sEAIC;AAED,oEAIC;AAED,kEAGC;AAED,wEAIC;AAED,sEAGC;AAED,8DAIC;AAED,kEAIC;AAED,0EAIC;AAED,kEAIC;AAED,oEAIC;AAED,0EAIC;AAED,8DAIC;AAED,0DAIC;AAED,sEAIC;AAED,oEAIC;AAED,gFAIC;AAED,0EAIC;AAED,gFAIC;AAED,4EAIC;AAED,gEAGC;AAED,oEAIC;AAED,wDAGC;AAED,0DAGC;AAED,sDAGC;AAED,0DAGC;AAED,gEAIC;AAED,8CAIC;AAED,gDAGC;AAED,kEAGC;AAED,kDAKC;AAED,wDAGC;AA7ND,4DAAmC;AA2BnC,SAAgB,cAAc;IAC5B,OAAO,IAAI,mBAAQ,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC;AAED,SAAgB,gBAAgB;IAC9B,OAAO,IAAI,mBAAQ,CAAC,2CAA2C,EAAE,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAgB,iCAAiC,CAAC,GAAa;IAC7D,MAAM,OAAO,GAAG,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC9E,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,yBAAyB,CAAC,GAAa;IACrD,MAAM,OAAO,GACX,mFAAmF,CAAC;IACtF,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC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,GAAG,GAAG,EAAE,IAAI,EAAE,MAAM,IAAI,gBAAgB,CAAC;IACzD,MAAM,OAAO,GAAG,6BAA6B,UAAU,4DAA4D,CAAC;IACpH,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,kBAAkB,CAAC,GAAa;IAC9C,MAAM,OAAO,GAAG,qGAAqG,CAAC;IACtH,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,2BAA2B,CAAC,GAAa;IACvD,MAAM,OAAO,GAAG,iGAAiG,CAAC;IAClH,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,mBAAmB,CAAC,GAAa;IAC/C,MAAM,KAAK,GAAG,GAAG,EAAE,IAAI,EAAE,KAAK,IAAI,eAAe,CAAC;IAClD,MAAM,YAAY,GAAG,GAAG,EAAE,IAAI,EAAE,aAAa,IAAI,cAAc,CAAC;IAChE,MAAM,OAAO,GAAG,gCAAgC,KAAK,qBAAqB,YAAY,GAAG,CAAC;IAC1F,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,sBAAsB,CAAC,GAAa;IAClD,MAAM,OAAO,GAAG,6FAA6F,CAAC;IAC9G,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string; // Prisma-specific error code\n message: string; // Error message\n meta?: Record<string, any>; // Metadata provided by Prisma\n name?: string; // Error name\n}\n\n// const handleCastErrorDB = (err: AppError) => {\n// const message = `Invalid ${err?.path}: ${err?.value}`\n// return new AppError(message, 400)\n// }\n\n// const handleDuplicateFieldDB = (err: AppError) => {\n// const value = err?.keyValue.name\n// const message = `Duplicate fiedl value: ${value}. Please use another value!`\n\n// return new AppError(message, 400)\n// }\n\n// const handleValidationErrorDB = (err: AppError) => {\n// const errors = Object.values(err?.errors).map((el) => el.message)\n// const message = `Ivalid input data. ${errors.join('. ')}`\n// return new AppError(message, 400)\n// }\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message = err?.message.split(\"\\n\")[err?.message.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(err: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(err: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(err: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(err: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(err: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(message, 409);\n}\n\nexport function handleForeignKeyConstraintError(err: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(err: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(err: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(err: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(err: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(err: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(err: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(err: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(err: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(err: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(err: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(err: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AASA,wCAEC;AAED,4CAEC;AAED,8EAGC;AAED,8DAIC;AAED,sEAIC;AAED,oEAIC;AAED,kEAGC;AAED,wEAIC;AAED,sEAGC;AAED,8DAIC;AAED,kEAIC;AAED,0EAIC;AAED,kEAIC;AAED,oEAIC;AAED,0EAIC;AAED,8DAIC;AAED,0DAIC;AAED,sEAIC;AAED,oEAIC;AAED,gFAIC;AAED,0EAIC;AAED,gFAIC;AAED,4EAIC;AAED,gEAGC;AAED,oEAIC;AAED,wDAGC;AAED,0DAGC;AAED,sDAGC;AAED,0DAGC;AAED,gEAIC;AAED,8CAIC;AAED,gDAGC;AAED,kEAGC;AAED,kDAKC;AAED,wDAGC;AA3MD,4DAAmC;AASnC,SAAgB,cAAc;IAC5B,OAAO,IAAI,mBAAQ,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC;AAED,SAAgB,gBAAgB;IAC9B,OAAO,IAAI,mBAAQ,CAAC,2CAA2C,EAAE,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAgB,iCAAiC,CAAC,GAAa;IAC7D,MAAM,OAAO,GAAG,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC9E,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,yBAAyB,CAAC,GAAa;IACrD,MAAM,OAAO,GACX,mFAAmF,CAAC;IACtF,OAAO,IAAI,mBAAQ,CAAC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gB,iBAAiB,CAAC,GAAa;IAC7C,MAAM,UAAU,GAAG,GAAG,EAAE,IAAI,EAAE,MAAM,IAAI,gBAAgB,CAAC;IACzD,MAAM,OAAO,GAAG,6BAA6B,UAAU,4DAA4D,CAAC;IACpH,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,kBAAkB,CAAC,GAAa;IAC9C,MAAM,OAAO,GAAG,qGAAqG,CAAC;IACtH,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,2BAA2B,CAAC,GAAa;IACvD,MAAM,OAAO,GAAG,iGAAiG,CAAC;IAClH,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,mBAAmB,CAAC,GAAa;IAC/C,MAAM,KAAK,GAAG,GAAG,EAAE,IAAI,EAAE,KAAK,IAAI,eAAe,CAAC;IAClD,MAAM,YAAY,GAAG,GAAG,EAAE,IAAI,EAAE,aAAa,IAAI,cAAc,CAAC;IAChE,MAAM,OAAO,GAAG,gCAAgC,KAAK,qBAAqB,YAAY,GAAG,CAAC;IAC1F,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,sBAAsB,CAAC,GAAa;IAClD,MAAM,OAAO,GAAG,6FAA6F,CAAC;IAC9G,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string; // Prisma-specific error code\n message: string; // Error message\n meta?: Record<string, any>; // Metadata provided by Prisma\n name?: string; // Error name\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message = err?.message.split(\"\\n\")[err?.message.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(err: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(err: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(err: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(err: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(err: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(message, 409);\n}\n\nexport function handleForeignKeyConstraintError(err: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(err: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(err: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(err: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(err: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(err: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(err: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(err: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(err: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(err: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(err: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(err: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n"]}
|
package/dist/cjs/server.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.server=void 0,exports.getArkosConfig=getArkosConfig,exports.getExpressApp=getExpressApp,exports.initApp=initApp;const app_1=require("./app"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper")),http_1=__importDefault(require("http"));process.on("uncaughtException",e=>{console.error(`
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.server=void 0,exports.terminateApplicationRunningProcessAndServer=terminateApplicationRunningProcessAndServer,exports.getArkosConfig=getArkosConfig,exports.getExpressApp=getExpressApp,exports.initApp=initApp;const app_1=require("./app"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper")),http_1=__importDefault(require("http"));process.on("uncaughtException",e=>{console.error(`
|
|
2
2
|
UNCAUGHT EXCEPTION! SHUTTING DOWN...
|
|
3
|
-
`),console.error(e.name,e.message),console.error(e),process.exit(1)});let server,_app,_arkosConfig={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:Number(process.env.CLI_PORT)||Number(process.env.PORT)||8e3,host:process.env.CLI_HOST||process.env.HOST||"localhost",fileUpload:{baseUploadDir:"uploads",baseRoute:"/api/uploads"},available:!1};async function initApp(e={}){_arkosConfig.available=!0,_arkosConfig=(0,deepmerge_helper_1.default)(_arkosConfig,e);const o=_arkosConfig.port;return _app=await(0,app_1.bootstrap)(_arkosConfig),o&&(exports.server=server=http_1.default.createServer(_app),_arkosConfig?.configureServer&&await _arkosConfig.configureServer(server),server.listen(o,_arkosConfig.host,()=>{const r=new Date().toTimeString().split(" ")[0];console.info(`
|
|
3
|
+
`),console.error(e.name,e.message),console.error(e),process.exit(1)});let server,_app,_arkosConfig={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:Number(process.env.CLI_PORT)||Number(process.env.PORT)||8e3,host:process.env.CLI_HOST||process.env.HOST||"localhost",fileUpload:{baseUploadDir:"uploads",baseRoute:"/api/uploads"},available:!1};async function initApp(e={}){_arkosConfig.available=!0,_arkosConfig=(0,deepmerge_helper_1.default)(_arkosConfig,e);const o=_arkosConfig.port;return _app=await(0,app_1.bootstrap)(_arkosConfig),o&&(exports.server=server=http_1.default.createServer(_app),_arkosConfig?.configureServer&&await _arkosConfig.configureServer(server),server.listen(o,_arkosConfig.host,()=>{const r=new Date().toTimeString().split(" ")[0];console.info(`
|
|
4
|
+
[\x1B[32mREADY\x1B[0m] \x1B[90m${r}\x1B[0m server waiting on http://${_arkosConfig.host||"localhost"}:${o}`)})),_app}process.on("unhandledRejection",e=>{console.error("UNHANDLED REJECTION! SHUTTING DOWN..."),console.error(e.name,e.message),console.error(e),server?.close(()=>{process.exit(1)})});function terminateApplicationRunningProcessAndServer(){server?.close(()=>{process.exit(1)})}function getArkosConfig(){return _arkosConfig}function getExpressApp(){return _app}
|
package/dist/cjs/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AAiFA,wCAEC;AAED,sCAEC;AAEgB,0BAAO;
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AAiFA,kGAIC;AAOD,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AAjGxB,+BAAkC;AAElC,wFAAyD;AACzD,gDAAwB;AAExB,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,0CAA0C,CAAC,CAAC;IAC1D,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEH,IAAI,MAA6D,CAAC;AAClE,I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AAED,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACvD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAOH,SAAgB,2CAA2C;IACzD,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAOD,SAAgB,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nlet _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig.available = true;\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port = _arkosConfig.port;\n _app = await bootstrap(_arkosConfig);\n\n if (port) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(port, _arkosConfig.host!, () => {\n const time = new Date().toTimeString().split(\" \")[0];\n console.info(\n `\\n[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m server waiting on http://${_arkosConfig.host || \"localhost\"}:${port}`\n );\n });\n }\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
|