arkos 1.1.88-test → 1.1.90-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/cli.js +0 -2
- package/dist/cjs/modules/base/base.service.js.map +1 -1
- package/dist/cjs/server.js +3 -1
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +6 -1
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/es2020/modules/base/base.service.js.map +1 -1
- package/dist/es2020/server.js +3 -1
- package/dist/es2020/server.js.map +1 -1
- package/dist/es2020/utils/helpers/models.helpers.js +6 -1
- package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
- package/dist/types/modules/base/base.service.d.ts +2 -2
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":";;;;;;AA2cA,0CAOC;AAldD,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;QAOvB,IAAI,IAAA,+BAAS,EAAC,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAK,IAAY,CAAC,QAAQ;YAChE,IAAI,CAAC,CAAC,MAAM,sBAAW,CAAC,gBAAgB,CAAE,IAAY,CAAC,QAAQ,CAAC,CAAC;gBAC9D,IAAY,CAAC,QAAQ,GAAG,MAAM,sBAAW,CAAC,YAAY,CACpD,IAAY,CAA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\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<TModel 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<TModel[\"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<TModel[\"create\"]>>} The created record.\n */\n async createOne<\n TOptions extends Omit<Parameters<TModel[\"create\"]>[0], \"data\">\n >(\n data: Parameters<TModel[\"create\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"create\"] extends (args: { data: any } & TOptions) => infer R\n ? R\n : any\n > {\n // user uer Password123 true false Promise { true }\n if (kebabCase(this.modelName) === \"user\" && (data as any).password)\n if (!(await 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].create(\n deepmerge(\n {\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { data: any } & TOptions\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Parameters<TModel[\"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<TModel[\"createMany\"]>>} The result of the createMany operation.\n */\n async createMany<\n TOptions extends Omit<Parameters<TModel[\"createMany\"]>[0], \"data\">\n >(\n data: Parameters<TModel[\"createMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"createMany\"] extends (args: { data: any } & TOptions) => 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 (!(await 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].createMany(\n deepmerge({ data }, (queryOptions as {}) || {}) as {\n data: any;\n } & TOptions\n );\n }\n\n /**\n * Counts records based on provided filters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"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].count({\n where: filters,\n });\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"findMany\"]>>} The found data.\n */\n async findMany<\n TOptions extends Omit<Parameters<TModel[\"findMany\"]>[0], \"where\">\n >(\n filters: Parameters<TModel[\"findMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findMany\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].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<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findById<\n TOptions extends Omit<Parameters<TModel[\"findUnique\"]>[0], \"where\">\n >(\n id: string | number,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findUnique\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].findUnique(\n deepmerge(\n {\n where: { id },\n },\n queryOptions || {}\n ) as { where: { id: string | number } } & TOptions\n );\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findOne<\n TOptions extends\n | Omit<Parameters<TModel[\"findFirst\"]>[0], \"where\">\n | Omit<Parameters<TModel[\"findUnique\"]>[0], \"where\">\n >(\n filters: Parameters<TModel[\"findFirst\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any | Parameters<TModel[\"findUnique\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findFirst\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : TModel[\"findUnique\"] extends (\n args: { where: any } & TOptions\n ) => 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].findUnique(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any } & TOptions\n );\n\n return await prisma[this.modelName].findFirst(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any } & TOptions\n );\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Parameters<TModel[\"update\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {Parameters<TModel[\"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<TModel[\"update\"]>>} The updated record or null if not found.\n */\n async updateOne<\n TOptions extends Omit<Parameters<TModel[\"update\"]>[0], \"where\" | \"data\">\n >(\n filters: Parameters<TModel[\"update\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<TModel[\"update\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"update\"] extends (\n args: { where: any; data: any } & TOptions\n ) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && (data as any)?.password) {\n if (!(await 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].update(\n deepmerge(\n {\n where: filters,\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { where: any; data: any } & TOptions\n );\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Parameters<TModel[\"updateMany\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The filters to identify records to update.\n * @param {Parameters<TModel[\"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<TModel[\"updateMany\"]>>} The result of the updateMany operation.\n */\n async updateMany<\n TOptions extends Omit<Parameters<TModel[\"updateMany\"]>[0], \"where\" | \"data\">\n >(\n filters: Parameters<TModel[\"updateMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<TModel[\"updateMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"updateMany\"] extends (\n args: { where: any; data: any } & TOptions\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 (!(await 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].updateMany(\n deepmerge({ where: filters }, firstMerge) as {\n where: any;\n data: any;\n } & TOptions\n );\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Parameters<TModel[\"delete\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @returns {Promise<ReturnType<TModel[\"delete\"]>>} The deleted record or null if an error occurs.\n */\n async deleteOne(\n filters: Parameters<TModel[\"delete\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<ReturnType<TModel[\"delete\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].delete({\n where: filters,\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Parameters<TModel[\"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<TModel[\"deleteMany\"]>>} The result of the deleteMany operation.\n */\n async deleteMany(\n filters: Parameters<TModel[\"deleteMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : Record<string, any>\n ): Promise<ReturnType<TModel[\"deleteMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].deleteMany({ where: filters });\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":";;;;;;AAycA,0CAOC;AAhdD,iFAIiD;AACjD,uEAI4C;AAC5C,4FAA6D;AAC7D,+EAAkF;AAClF,uEAAuE;AACvE,wEAA+C;AAuB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B,GAAE,CAAC;QAEnC,OAAO,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IACrE,CAAC;CACF;AA9ZD,kCA8ZC;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<TModel 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<TModel[\"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<TModel[\"create\"]>>} The created record.\n */\n async createOne<\n TOptions extends Omit<Parameters<TModel[\"create\"]>[0], \"data\">\n >(\n data: Parameters<TModel[\"create\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"create\"] extends (args: { data: any } & TOptions) => infer R\n ? R\n : any\n > {\n // user uer Password123 true false Promise { true }\n if (kebabCase(this.modelName) === \"user\" && (data as any).password)\n if (!(await 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].create(\n deepmerge(\n {\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { data: any } & TOptions\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Parameters<TModel[\"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<TModel[\"createMany\"]>>} The result of the createMany operation.\n */\n async createMany<\n TOptions extends Omit<Parameters<TModel[\"createMany\"]>[0], \"data\">\n >(\n data: Parameters<TModel[\"createMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"createMany\"] extends (args: { data: any } & TOptions) => 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 (!(await 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].createMany(\n deepmerge({ data }, (queryOptions as {}) || {}) as {\n data: any;\n } & TOptions\n );\n }\n\n /**\n * Counts records based on provided filters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"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].count({\n where: filters,\n });\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"findMany\"]>>} The found data.\n */\n async findMany<\n TOptions extends Omit<Parameters<TModel[\"findMany\"]>[0], \"where\">\n >(\n filters: Parameters<TModel[\"findMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findMany\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].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<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findById<\n TOptions extends Omit<Parameters<TModel[\"findUnique\"]>[0], \"where\">\n >(\n id: string | number,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findUnique\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].findUnique(\n deepmerge(\n {\n where: { id },\n },\n queryOptions || {}\n ) as { where: { id: string | number } } & TOptions\n );\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findOne<\n TOptions extends\n | Omit<Parameters<TModel[\"findFirst\"]>[0], \"where\">\n | Omit<Parameters<TModel[\"findUnique\"]>[0], \"where\">\n >(\n filters: Parameters<TModel[\"findFirst\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any | Parameters<TModel[\"findUnique\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findFirst\"] extends (args: { where: any }) => infer R\n ? R\n : TModel[\"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].findUnique(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any } & TOptions\n );\n\n return await prisma[this.modelName].findFirst(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any } & TOptions\n );\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Parameters<TModel[\"update\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {Parameters<TModel[\"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<TModel[\"update\"]>>} The updated record or null if not found.\n */\n async updateOne<\n TOptions extends Omit<Parameters<TModel[\"update\"]>[0], \"where\" | \"data\">\n >(\n filters: Parameters<TModel[\"update\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<TModel[\"update\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"update\"] extends (\n args: { where: any; data: any } & TOptions\n ) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && (data as any)?.password) {\n if (!(await 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].update(\n deepmerge(\n {\n where: filters,\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { where: any; data: any } & TOptions\n );\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Parameters<TModel[\"updateMany\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The filters to identify records to update.\n * @param {Parameters<TModel[\"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<TModel[\"updateMany\"]>>} The result of the updateMany operation.\n */\n async updateMany<\n TOptions extends Omit<Parameters<TModel[\"updateMany\"]>[0], \"where\" | \"data\">\n >(\n filters: Parameters<TModel[\"updateMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<TModel[\"updateMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"updateMany\"] extends (\n args: { where: any; data: any } & TOptions\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 (!(await 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].updateMany(\n deepmerge({ where: filters }, firstMerge) as {\n where: any;\n data: any;\n } & TOptions\n );\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Parameters<TModel[\"delete\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @returns {Promise<ReturnType<TModel[\"delete\"]>>} The deleted record or null if an error occurs.\n */\n async deleteOne(\n filters: Parameters<TModel[\"delete\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<ReturnType<TModel[\"delete\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].delete({\n where: filters,\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Parameters<TModel[\"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<TModel[\"deleteMany\"]>>} The result of the deleteMany operation.\n */\n async deleteMany(\n filters: Parameters<TModel[\"deleteMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : Record<string, any>\n ): Promise<ReturnType<TModel[\"deleteMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].deleteMany({ where: filters });\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"]}
|
package/dist/cjs/server.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.server=void 0,exports.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.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
|
+
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(`[\x1B[32mREADY\x1B[0m] \x1B[90m${r}\x1B[0m server waiting on http://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 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;AAtFxB,+BAAkC;AAElC,wFAAyD;AACzD,gDAAwB;AAExB,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AAiFA,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AAtFxB,+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,IAAI,IAAa,CAAC;AAEl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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,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 `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m server waiting on http://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 * 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"]}
|
|
@@ -187,7 +187,12 @@ async function importPrismaModelModules(modelName) {
|
|
|
187
187
|
await Promise.all(Object.entries(fileStructure.core).map(async ([key, fileName]) => {
|
|
188
188
|
const filePath = path_1.default.join(moduleDir, fileName);
|
|
189
189
|
try {
|
|
190
|
-
const module = await (0, global_helpers_1.importModule)(filePath).catch(() =>
|
|
190
|
+
const module = await (0, global_helpers_1.importModule)(filePath).catch((err) => {
|
|
191
|
+
if (!err.message.includes("Cannot find module")) {
|
|
192
|
+
console.error(`\n${err?.message}`);
|
|
193
|
+
throw err;
|
|
194
|
+
}
|
|
195
|
+
});
|
|
191
196
|
if (module) {
|
|
192
197
|
validateNamingConventions(key, fileName, result);
|
|
193
198
|
assignModuleToResult(key, module, result);
|
|
@@ -1 +1 @@
|
|
|
1
|
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M,EAGpB,CAAC;oBACD,SAAS;gBACX,CAAC;gBAED,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;oBAC5B,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;wBACtB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;wBAClB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,iCAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC;AAED,sBAAsB,EAAE,CAAC;AAQzB,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,iCAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,iCAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,cAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,gCAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n authConfigsNew: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n prismaQueryOptionsNew: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n console.error(error);\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n console.error(error);\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: any;\n prismaQueryOptionsNew?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {importPrismaModelModulesReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\") {\n if (result.prismaQueryOptions) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"prisma-query-options\",\n \"query\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"prismaQueryOptionsNew\") {\n if (result.prismaQueryOptions) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"query\",\n \"prisma-query-options\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigs\") {\n if (result.authConfigs) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth-configs\",\n \"auth\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigsNew\") {\n if (result.authConfigs) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth\",\n \"auth-configs\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {importPrismaModelModulesReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n key: string,\n module: any,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\" || key === \"prismaQueryOptionsNew\") {\n result.prismaQueryOptions = module.default || module;\n } else if (key === \"authConfigs\" || key === \"authConfigsNew\") {\n result.authConfigs = module.default || module;\n } else if (key === \"middlewares\" || key === \"router\") {\n result[key] = module;\n } else {\n result[key as keyof typeof result] = module.default || module;\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n\n if (module) {\n // Validate naming conventions before assignment\n validateNamingConventions(key, fileName, result);\n\n // Assign module to result\n assignModuleToResult(key, module, result);\n }\n } catch (err: any) {\n if (err.message.includes(\"Cannot use both\")) throw err;\n console.error(err);\n }\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\n// /**\n// * Dynamically imports model-specific modules for a given model with optimized file handling.\n// * Includes special handling for the Auth module.\n// *\n// * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n// * @returns {Promise<Object>} An object containing the imported modules\n// */\n// export async function importPrismaModelModules(\n// modelName: string\n// ): Promise<importPrismaModelModulesReturnType> {\n// const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n// const result: importPrismaModelModulesReturnType = {\n// dtos: {},\n// schemas: {},\n// };\n\n// const fileStructure = getFileModelModulesFileStructure(modelName);\n// // Batch process core files\n// await Promise.all(\n// Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n// const filePath = path.join(moduleDir, fileName);\n// try {\n// const module = await importModule(filePath).catch(() => null);\n\n// if (module) {\n// // Handle prismaQueryOptions (old vs new naming)\n// if (key === \"prismaQueryOptions\") {\n// if (result.prismaQueryOptions) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"prisma-query-options\",\n// \"query\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// result.prismaQueryOptions = module.default || module;\n// } else if (key === \"prismaQueryOptionsNew\") {\n// if (result.prismaQueryOptions) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"query\",\n// \"prisma-query-options\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// // Store new naming convention under old key\n// result.prismaQueryOptions = module.default || module;\n// }\n// // Handle authConfigs (old vs new naming)\n// else if (key === \"authConfigs\") {\n// if (result.authConfigs) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"auth-configs\",\n// \"auth\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// result.authConfigs = module.default || module;\n// } else if (key === \"authConfigsNew\") {\n// if (result.authConfigs) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"auth\",\n// \"auth-configs\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// // Store new naming convention under old key\n// result.authConfigs = module.default || module;\n// }\n// // Handle other modules\n// else if (key === \"middlewares\" || key === \"router\") {\n// result[key] = module;\n// } else {\n// result[key as keyof typeof result] = module.default || module;\n// }\n// }\n// } catch (err: any) {\n// if (err.message.includes(\"Cannot use both\")) throw err;\n// console.error(err);\n// }\n// })\n// );\n\n// await Promise.all([\n// processSubdir(modelName, \"dtos\", result),\n// processSubdir(modelName, \"schemas\", result),\n// ]);\n\n// // Cache the result\n// prismaModelsModules[modelName] = result;\n\n// return result;\n// }\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels() {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\") ||\n trimmedLine.startsWith(\"/*\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine?.includes?.(\"@unique\");\n\n if (isUnique) {\n const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\n }\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine?.includes?.(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models?.includes?.(camelCase(cleanType || \"\"))\n ) {\n const enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n\n // && !content.includes?.(`model ${cleanType} {`)\n ) {\n continue;\n }\n\n if (!type?.includes?.(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n }\n}\n\ninitializePrismaModels();\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
1
|
+
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,0CAEC;AAED,4EA+CC;AAED,sCAqDC;AAsBD,8DA0CC;AAQD,oDAcC;AASD,4DAgDC;AA4HD,8CAgBC;AAOD,wDA6GC;AAUD,0DAKC;AAmBQ,8BAAS;AAAE,oDAAoB;AA3iBxC,gDAAwB;AACxB,4CAAoB;AACpB,iFAIiD;AACjD,6CAAyD;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Q,CAAC,IAAI,CAAC;wBACtB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;wBAClB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,iCAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC;AAED,sBAAsB,EAAE,CAAC;AAQzB,SAAgB,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,iCAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,iCAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,cAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,gCAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n authConfigsNew: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n prismaQueryOptionsNew: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n console.error(error);\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n console.error(error);\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: any;\n prismaQueryOptionsNew?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {importPrismaModelModulesReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\") {\n if (result.prismaQueryOptions) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"prisma-query-options\",\n \"query\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"prismaQueryOptionsNew\") {\n if (result.prismaQueryOptions) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"query\",\n \"prisma-query-options\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigs\") {\n if (result.authConfigs) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth-configs\",\n \"auth\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigsNew\") {\n if (result.authConfigs) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth\",\n \"auth-configs\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {importPrismaModelModulesReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n key: string,\n module: any,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\" || key === \"prismaQueryOptionsNew\") {\n result.prismaQueryOptions = module.default || module;\n } else if (key === \"authConfigs\" || key === \"authConfigsNew\") {\n result.authConfigs = module.default || module;\n } else if (key === \"middlewares\" || key === \"router\") {\n result[key] = module;\n } else {\n result[key as keyof typeof result] = module.default || module;\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch((err) => {\n if (!err.message.includes(\"Cannot find module\")) {\n console.error(`\\n${err?.message}`);\n throw err;\n // process.exit(1);\n }\n });\n\n if (module) {\n // Validate naming conventions before assignment\n validateNamingConventions(key, fileName, result);\n\n // Assign module to result\n assignModuleToResult(key, module, result);\n }\n } catch (err: any) {\n if (err.message.includes(\"Cannot use both\")) throw err;\n console.error(err);\n }\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\n// /**\n// * Dynamically imports model-specific modules for a given model with optimized file handling.\n// * Includes special handling for the Auth module.\n// *\n// * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n// * @returns {Promise<Object>} An object containing the imported modules\n// */\n// export async function importPrismaModelModules(\n// modelName: string\n// ): Promise<importPrismaModelModulesReturnType> {\n// const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n// const result: importPrismaModelModulesReturnType = {\n// dtos: {},\n// schemas: {},\n// };\n\n// const fileStructure = getFileModelModulesFileStructure(modelName);\n// // Batch process core files\n// await Promise.all(\n// Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n// const filePath = path.join(moduleDir, fileName);\n// try {\n// const module = await importModule(filePath).catch(() => null);\n\n// if (module) {\n// // Handle prismaQueryOptions (old vs new naming)\n// if (key === \"prismaQueryOptions\") {\n// if (result.prismaQueryOptions) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"prisma-query-options\",\n// \"query\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// result.prismaQueryOptions = module.default || module;\n// } else if (key === \"prismaQueryOptionsNew\") {\n// if (result.prismaQueryOptions) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"query\",\n// \"prisma-query-options\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// // Store new naming convention under old key\n// result.prismaQueryOptions = module.default || module;\n// }\n// // Handle authConfigs (old vs new naming)\n// else if (key === \"authConfigs\") {\n// if (result.authConfigs) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"auth-configs\",\n// \"auth\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// result.authConfigs = module.default || module;\n// } else if (key === \"authConfigsNew\") {\n// if (result.authConfigs) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"auth\",\n// \"auth-configs\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// // Store new naming convention under old key\n// result.authConfigs = module.default || module;\n// }\n// // Handle other modules\n// else if (key === \"middlewares\" || key === \"router\") {\n// result[key] = module;\n// } else {\n// result[key as keyof typeof result] = module.default || module;\n// }\n// }\n// } catch (err: any) {\n// if (err.message.includes(\"Cannot use both\")) throw err;\n// console.error(err);\n// }\n// })\n// );\n\n// await Promise.all([\n// processSubdir(modelName, \"dtos\", result),\n// processSubdir(modelName, \"schemas\", result),\n// ]);\n\n// // Cache the result\n// prismaModelsModules[modelName] = result;\n\n// return result;\n// }\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels() {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\") ||\n trimmedLine.startsWith(\"/*\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine?.includes?.(\"@unique\");\n\n if (isUnique) {\n const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\n }\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine?.includes?.(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models?.includes?.(camelCase(cleanType || \"\"))\n ) {\n const enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n\n // && !content.includes?.(`model ${cleanType} {`)\n ) {\n continue;\n }\n\n if (!type?.includes?.(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n }\n}\n\ninitializePrismaModels();\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,GACX,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,SAAS,EACT,uBAAuB,GAExB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,sCAAsC,CAAC;AAClF,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,WAAW,MAAM,sBAAs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e;IAC7B,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,YAAY,GAAqC,EAAE,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport {\n getModels,\n getPrismaModelRelations,\n RelationFields,\n} from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { handleRelationFieldsInBody } from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n *\n * by model-specific service classes.\n *\n * @class BaseService\n *\n * @usage\n *\n * **Example:** creating a simple service\n *\n * ```ts\n * import { prisma } from '../../utils/prisma'\n *\n * const userService = new BaseService<typeof prisma.user>(\"user\")\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-service-class}\n *\n */\nexport class BaseService<TModel 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<TModel[\"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<TModel[\"create\"]>>} The created record.\n */\n async createOne<\n TOptions extends Omit<Parameters<TModel[\"create\"]>[0], \"data\">\n >(\n data: Parameters<TModel[\"create\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"create\"] extends (args: { data: any } & TOptions) => infer R\n ? R\n : any\n > {\n // user uer Password123 true false Promise { true }\n if (kebabCase(this.modelName) === \"user\" && (data as any).password)\n if (!(await 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].create(\n deepmerge(\n {\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { data: any } & TOptions\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Parameters<TModel[\"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<TModel[\"createMany\"]>>} The result of the createMany operation.\n */\n async createMany<\n TOptions extends Omit<Parameters<TModel[\"createMany\"]>[0], \"data\">\n >(\n data: Parameters<TModel[\"createMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"createMany\"] extends (args: { data: any } & TOptions) => 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 (!(await 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].createMany(\n deepmerge({ data }, (queryOptions as {}) || {}) as {\n data: any;\n } & TOptions\n );\n }\n\n /**\n * Counts records based on provided filters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"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].count({\n where: filters,\n });\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"findMany\"]>>} The found data.\n */\n async findMany<\n TOptions extends Omit<Parameters<TModel[\"findMany\"]>[0], \"where\">\n >(\n filters: Parameters<TModel[\"findMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findMany\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].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<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findById<\n TOptions extends Omit<Parameters<TModel[\"findUnique\"]>[0], \"where\">\n >(\n id: string | number,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findUnique\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].findUnique(\n deepmerge(\n {\n where: { id },\n },\n queryOptions || {}\n ) as { where: { id: string | number } } & TOptions\n );\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findOne<\n TOptions extends\n | Omit<Parameters<TModel[\"findFirst\"]>[0], \"where\">\n | Omit<Parameters<TModel[\"findUnique\"]>[0], \"where\">\n >(\n filters: Parameters<TModel[\"findFirst\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any | Parameters<TModel[\"findUnique\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findFirst\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : TModel[\"findUnique\"] extends (\n args: { where: any } & TOptions\n ) => 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].findUnique(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any } & TOptions\n );\n\n return await prisma[this.modelName].findFirst(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any } & TOptions\n );\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Parameters<TModel[\"update\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {Parameters<TModel[\"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<TModel[\"update\"]>>} The updated record or null if not found.\n */\n async updateOne<\n TOptions extends Omit<Parameters<TModel[\"update\"]>[0], \"where\" | \"data\">\n >(\n filters: Parameters<TModel[\"update\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<TModel[\"update\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"update\"] extends (\n args: { where: any; data: any } & TOptions\n ) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && (data as any)?.password) {\n if (!(await 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].update(\n deepmerge(\n {\n where: filters,\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { where: any; data: any } & TOptions\n );\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Parameters<TModel[\"updateMany\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The filters to identify records to update.\n * @param {Parameters<TModel[\"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<TModel[\"updateMany\"]>>} The result of the updateMany operation.\n */\n async updateMany<\n TOptions extends Omit<Parameters<TModel[\"updateMany\"]>[0], \"where\" | \"data\">\n >(\n filters: Parameters<TModel[\"updateMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<TModel[\"updateMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"updateMany\"] extends (\n args: { where: any; data: any } & TOptions\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 (!(await 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].updateMany(\n deepmerge({ where: filters }, firstMerge) as {\n where: any;\n data: any;\n } & TOptions\n );\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Parameters<TModel[\"delete\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @returns {Promise<ReturnType<TModel[\"delete\"]>>} The deleted record or null if an error occurs.\n */\n async deleteOne(\n filters: Parameters<TModel[\"delete\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<ReturnType<TModel[\"delete\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].delete({\n where: filters,\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Parameters<TModel[\"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<TModel[\"deleteMany\"]>>} The result of the deleteMany operation.\n */\n async deleteMany(\n filters: Parameters<TModel[\"deleteMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : Record<string, any>\n ): Promise<ReturnType<TModel[\"deleteMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].deleteMany({ where: filters });\n }\n}\n\n/**\n * Generates a set of base service instances for all available models.\n *\n * @returns {Record<string, BaseService>} A dictionary of base service instances, keyed by model name.\n */\nexport function getBaseServices(): Record<string, BaseService<any>> {\n const models = getModels();\n const baseServices: Record<string, BaseService<any>> = {};\n models.forEach((model) => {\n baseServices[`${camelCase(model)}`] = new BaseService(model);\n });\n return baseServices;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,GACX,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,SAAS,EACT,uBAAuB,GAExB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,sCAAsC,CAAC;AAClF,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,WAAW,MAAM,sBAAsB,CAAC;AAuB/C,MAAM,OAAO,WAAW;IAuBtB,YAAY,SAAiB;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,cAAc,GAAG,uBAAuB,CAAC,UAAU,CAAC,SAAS,CAAC,CAAE,CAAC;IACxE,CAAC;IASD,KAAK,CAAC,SAAS,CAGb,IAKO,EACP,YAAuB;QAOvB,IAAI,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAK,IAAY,CAAC,QAAQ;YAChE,IAAI,CAAC,CAAC,MAAM,WAAW,CAAC,gBAAgB,CAAE,IAAY,CAAC,QAAQ,CAAC,CAAC;gBAC9D,IAAY,CAAC,QAAQ,GAAG,MAAM,WAAW,CAAC,YAAY,CACpD,IAAY,CAAC,QAAQ,CACvB,CAAC;QAEN,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAC;QAEnC,MAAM,6BAA6B,GAAG,0BAA0B,CAC9D,IAA2B,EAC3B;YACE,GAAG,IAAI,CAAC,cAAc;SACvB,EACD,CAAC,QAAQ,EAAE,YAAY,EAAE,QAAQ,CAAC,C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AAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,UAAU,CAG5B,CACb,CAAC;IACJ,CAAC;IAQD,KAAK,CAAC,SAAS,CACb,OAKO;QAEP,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAC;QAEnC,OAAO,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC;YACzC,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC;IAQD,KAAK,CAAC,UAAU,CACd,OAKuB;QAEvB,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAC;QAEnC,OAAO,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IACrE,CAAC;CACF;AAOD,MAAM,UAAU,eAAe;IAC7B,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,YAAY,GAAqC,EAAE,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport {\n getModels,\n getPrismaModelRelations,\n RelationFields,\n} from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { handleRelationFieldsInBody } from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n *\n * by model-specific service classes.\n *\n * @class BaseService\n *\n * @usage\n *\n * **Example:** creating a simple service\n *\n * ```ts\n * import { prisma } from '../../utils/prisma'\n *\n * const userService = new BaseService<typeof prisma.user>(\"user\")\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-service-class}\n *\n */\nexport class BaseService<TModel 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<TModel[\"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<TModel[\"create\"]>>} The created record.\n */\n async createOne<\n TOptions extends Omit<Parameters<TModel[\"create\"]>[0], \"data\">\n >(\n data: Parameters<TModel[\"create\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"create\"] extends (args: { data: any } & TOptions) => infer R\n ? R\n : any\n > {\n // user uer Password123 true false Promise { true }\n if (kebabCase(this.modelName) === \"user\" && (data as any).password)\n if (!(await 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].create(\n deepmerge(\n {\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { data: any } & TOptions\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Parameters<TModel[\"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<TModel[\"createMany\"]>>} The result of the createMany operation.\n */\n async createMany<\n TOptions extends Omit<Parameters<TModel[\"createMany\"]>[0], \"data\">\n >(\n data: Parameters<TModel[\"createMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"createMany\"] extends (args: { data: any } & TOptions) => 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 (!(await 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].createMany(\n deepmerge({ data }, (queryOptions as {}) || {}) as {\n data: any;\n } & TOptions\n );\n }\n\n /**\n * Counts records based on provided filters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"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].count({\n where: filters,\n });\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"findMany\"]>>} The found data.\n */\n async findMany<\n TOptions extends Omit<Parameters<TModel[\"findMany\"]>[0], \"where\">\n >(\n filters: Parameters<TModel[\"findMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findMany\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].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<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findById<\n TOptions extends Omit<Parameters<TModel[\"findUnique\"]>[0], \"where\">\n >(\n id: string | number,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findUnique\"] extends (args: { where: any } & TOptions) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].findUnique(\n deepmerge(\n {\n where: { id },\n },\n queryOptions || {}\n ) as { where: { id: string | number } } & TOptions\n );\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Parameters<TModel[\"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<TModel[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findOne<\n TOptions extends\n | Omit<Parameters<TModel[\"findFirst\"]>[0], \"where\">\n | Omit<Parameters<TModel[\"findUnique\"]>[0], \"where\">\n >(\n filters: Parameters<TModel[\"findFirst\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any | Parameters<TModel[\"findUnique\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"findFirst\"] extends (args: { where: any }) => infer R\n ? R\n : TModel[\"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].findUnique(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any } & TOptions\n );\n\n return await prisma[this.modelName].findFirst(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any } & TOptions\n );\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Parameters<TModel[\"update\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {Parameters<TModel[\"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<TModel[\"update\"]>>} The updated record or null if not found.\n */\n async updateOne<\n TOptions extends Omit<Parameters<TModel[\"update\"]>[0], \"where\" | \"data\">\n >(\n filters: Parameters<TModel[\"update\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<TModel[\"update\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"update\"] extends (\n args: { where: any; data: any } & TOptions\n ) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && (data as any)?.password) {\n if (!(await 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].update(\n deepmerge(\n {\n where: filters,\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { where: any; data: any } & TOptions\n );\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Parameters<TModel[\"updateMany\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The filters to identify records to update.\n * @param {Parameters<TModel[\"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<TModel[\"updateMany\"]>>} The result of the updateMany operation.\n */\n async updateMany<\n TOptions extends Omit<Parameters<TModel[\"updateMany\"]>[0], \"where\" | \"data\">\n >(\n filters: Parameters<TModel[\"updateMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<TModel[\"updateMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n TModel[\"updateMany\"] extends (\n args: { where: any; data: any } & TOptions\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 (!(await 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].updateMany(\n deepmerge({ where: filters }, firstMerge) as {\n where: any;\n data: any;\n } & TOptions\n );\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Parameters<TModel[\"delete\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @returns {Promise<ReturnType<TModel[\"delete\"]>>} The deleted record or null if an error occurs.\n */\n async deleteOne(\n filters: Parameters<TModel[\"delete\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<ReturnType<TModel[\"delete\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].delete({\n where: filters,\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Parameters<TModel[\"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<TModel[\"deleteMany\"]>>} The result of the deleteMany operation.\n */\n async deleteMany(\n filters: Parameters<TModel[\"deleteMany\"]>[0] extends {\n where: infer W;\n [x: string]: any;\n }\n ? W\n : Record<string, any>\n ): Promise<ReturnType<TModel[\"deleteMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].deleteMany({ where: filters });\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"]}
|
package/dist/es2020/server.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
"use strict";import{bootstrap as a}from"./app";import p from"./utils/helpers/deepmerge.helper";import i from"http";process.on("uncaughtException",e=>{console.error(
|
|
1
|
+
"use strict";import{bootstrap as a}from"./app";import p from"./utils/helpers/deepmerge.helper";import i from"http";process.on("uncaughtException",e=>{console.error(`
|
|
2
|
+
UNCAUGHT EXCEPTION! SHUTTING DOWN...
|
|
3
|
+
`),console.error(e.name,e.message),console.error(e),process.exit(1)});let r,s,o={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 c(e={}){o.available=!0,o=p(o,e);const t=o.port;return s=await a(o),t&&(r=i.createServer(s),o?.configureServer&&await o.configureServer(r),r.listen(t,o.host,()=>{const n=new Date().toTimeString().split(" ")[0];console.info(`[\x1B[32mREADY\x1B[0m] \x1B[90m${n}\x1B[0m server waiting on http://localhost:${t}`)})),s}process.on("unhandledRejection",e=>{console.error("UNHANDLED REJECTION! SHUTTING DOWN..."),console.error(e.name,e.message),console.error(e),r?.close(()=>{process.exit(1)})});export function getArkosConfig(){return o}export function getExpressApp(){return s}export{r as server,c as initApp};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CAAC;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,IAAI,IAAa,CAAC;AAElB,IAAI,YAAY,GAA0C;IACxD,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,GAA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,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,MAAM,UAAU,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,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 `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m server waiting on http://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 * 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"]}
|
|
@@ -137,7 +137,12 @@ export async function importPrismaModelModules(modelName) {
|
|
|
137
137
|
await Promise.all(Object.entries(fileStructure.core).map(async ([key, fileName]) => {
|
|
138
138
|
const filePath = path.join(moduleDir, fileName);
|
|
139
139
|
try {
|
|
140
|
-
const module = await importModule(filePath).catch(() =>
|
|
140
|
+
const module = await importModule(filePath).catch((err) => {
|
|
141
|
+
if (!err.message.includes("Cannot find module")) {
|
|
142
|
+
console.error(`\n${err?.message}`);
|
|
143
|
+
throw err;
|
|
144
|
+
}
|
|
145
|
+
});
|
|
141
146
|
if (module) {
|
|
142
147
|
validateNamingConventions(key, fileName, result);
|
|
143
148
|
assignModuleToResult(key, module, result);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":"AAAA,OAAO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AAI,CAAC,EAAE,CAAC;oBAC5B,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;wBACtB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;wBAClB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,yBAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC;AAED,sBAAsB,EAAE,CAAC;AAQzB,MAAM,UAAU,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,yBAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,yBAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,MAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,wBAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC;AAED,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n authConfigsNew: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n prismaQueryOptionsNew: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n console.error(error);\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n console.error(error);\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: any;\n prismaQueryOptionsNew?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {importPrismaModelModulesReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\") {\n if (result.prismaQueryOptions) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"prisma-query-options\",\n \"query\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"prismaQueryOptionsNew\") {\n if (result.prismaQueryOptions) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"query\",\n \"prisma-query-options\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigs\") {\n if (result.authConfigs) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth-configs\",\n \"auth\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigsNew\") {\n if (result.authConfigs) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth\",\n \"auth-configs\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {importPrismaModelModulesReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n key: string,\n module: any,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\" || key === \"prismaQueryOptionsNew\") {\n result.prismaQueryOptions = module.default || module;\n } else if (key === \"authConfigs\" || key === \"authConfigsNew\") {\n result.authConfigs = module.default || module;\n } else if (key === \"middlewares\" || key === \"router\") {\n result[key] = module;\n } else {\n result[key as keyof typeof result] = module.default || module;\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n\n if (module) {\n // Validate naming conventions before assignment\n validateNamingConventions(key, fileName, result);\n\n // Assign module to result\n assignModuleToResult(key, module, result);\n }\n } catch (err: any) {\n if (err.message.includes(\"Cannot use both\")) throw err;\n console.error(err);\n }\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\n// /**\n// * Dynamically imports model-specific modules for a given model with optimized file handling.\n// * Includes special handling for the Auth module.\n// *\n// * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n// * @returns {Promise<Object>} An object containing the imported modules\n// */\n// export async function importPrismaModelModules(\n// modelName: string\n// ): Promise<importPrismaModelModulesReturnType> {\n// const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n// const result: importPrismaModelModulesReturnType = {\n// dtos: {},\n// schemas: {},\n// };\n\n// const fileStructure = getFileModelModulesFileStructure(modelName);\n// // Batch process core files\n// await Promise.all(\n// Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n// const filePath = path.join(moduleDir, fileName);\n// try {\n// const module = await importModule(filePath).catch(() => null);\n\n// if (module) {\n// // Handle prismaQueryOptions (old vs new naming)\n// if (key === \"prismaQueryOptions\") {\n// if (result.prismaQueryOptions) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"prisma-query-options\",\n// \"query\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// result.prismaQueryOptions = module.default || module;\n// } else if (key === \"prismaQueryOptionsNew\") {\n// if (result.prismaQueryOptions) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"query\",\n// \"prisma-query-options\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// // Store new naming convention under old key\n// result.prismaQueryOptions = module.default || module;\n// }\n// // Handle authConfigs (old vs new naming)\n// else if (key === \"authConfigs\") {\n// if (result.authConfigs) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"auth-configs\",\n// \"auth\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// result.authConfigs = module.default || module;\n// } else if (key === \"authConfigsNew\") {\n// if (result.authConfigs) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"auth\",\n// \"auth-configs\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// // Store new naming convention under old key\n// result.authConfigs = module.default || module;\n// }\n// // Handle other modules\n// else if (key === \"middlewares\" || key === \"router\") {\n// result[key] = module;\n// } else {\n// result[key as keyof typeof result] = module.default || module;\n// }\n// }\n// } catch (err: any) {\n// if (err.message.includes(\"Cannot use both\")) throw err;\n// console.error(err);\n// }\n// })\n// );\n\n// await Promise.all([\n// processSubdir(modelName, \"dtos\", result),\n// processSubdir(modelName, \"schemas\", result),\n// ]);\n\n// // Cache the result\n// prismaModelsModules[modelName] = result;\n\n// return result;\n// }\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels() {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\") ||\n trimmedLine.startsWith(\"/*\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine?.includes?.(\"@unique\");\n\n if (isUnique) {\n const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\n }\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine?.includes?.(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models?.includes?.(camelCase(cleanType || \"\"))\n ) {\n const enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n\n // && !content.includes?.(`model ${cleanType} {`)\n ) {\n continue;\n }\n\n if (!type?.includes?.(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n }\n}\n\ninitializePrismaModels();\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
1
|
+
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,GACX,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAGhD,MAAM,CAAC,IAAI,mBAAmB,GAG1B,EAAE,CAAC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AS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;wBAClB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,SAAS;qBAChB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,yBAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;QACnD,CAAC;IACH,CAAC;AACH,CAAC;AAED,sBAAsB,EAAE,CAAC;AAQzB,MAAM,UAAU,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,yBAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,yBAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,MAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,wBAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC;AAED,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n authConfigsNew: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n prismaQueryOptionsNew: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n console.error(error);\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n console.error(error);\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: any;\n prismaQueryOptionsNew?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {importPrismaModelModulesReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\") {\n if (result.prismaQueryOptions) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"prisma-query-options\",\n \"query\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"prismaQueryOptionsNew\") {\n if (result.prismaQueryOptions) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"query\",\n \"prisma-query-options\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigs\") {\n if (result.authConfigs) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth-configs\",\n \"auth\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n } else if (key === \"authConfigsNew\") {\n if (result.authConfigs) {\n throw new Error(\n `\\n Cannot use both ${fileName} and ${fileName.replace(\n \"auth\",\n \"auth-configs\"\n )} at once, please choose only one name convention. \\n`\n );\n }\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {importPrismaModelModulesReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n key: string,\n module: any,\n result: importPrismaModelModulesReturnType\n): void {\n if (key === \"prismaQueryOptions\" || key === \"prismaQueryOptionsNew\") {\n result.prismaQueryOptions = module.default || module;\n } else if (key === \"authConfigs\" || key === \"authConfigsNew\") {\n result.authConfigs = module.default || module;\n } else if (key === \"middlewares\" || key === \"router\") {\n result[key] = module;\n } else {\n result[key as keyof typeof result] = module.default || module;\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch((err) => {\n if (!err.message.includes(\"Cannot find module\")) {\n console.error(`\\n${err?.message}`);\n throw err;\n // process.exit(1);\n }\n });\n\n if (module) {\n // Validate naming conventions before assignment\n validateNamingConventions(key, fileName, result);\n\n // Assign module to result\n assignModuleToResult(key, module, result);\n }\n } catch (err: any) {\n if (err.message.includes(\"Cannot use both\")) throw err;\n console.error(err);\n }\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\n// /**\n// * Dynamically imports model-specific modules for a given model with optimized file handling.\n// * Includes special handling for the Auth module.\n// *\n// * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n// * @returns {Promise<Object>} An object containing the imported modules\n// */\n// export async function importPrismaModelModules(\n// modelName: string\n// ): Promise<importPrismaModelModulesReturnType> {\n// const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n// const result: importPrismaModelModulesReturnType = {\n// dtos: {},\n// schemas: {},\n// };\n\n// const fileStructure = getFileModelModulesFileStructure(modelName);\n// // Batch process core files\n// await Promise.all(\n// Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n// const filePath = path.join(moduleDir, fileName);\n// try {\n// const module = await importModule(filePath).catch(() => null);\n\n// if (module) {\n// // Handle prismaQueryOptions (old vs new naming)\n// if (key === \"prismaQueryOptions\") {\n// if (result.prismaQueryOptions) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"prisma-query-options\",\n// \"query\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// result.prismaQueryOptions = module.default || module;\n// } else if (key === \"prismaQueryOptionsNew\") {\n// if (result.prismaQueryOptions) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"query\",\n// \"prisma-query-options\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// // Store new naming convention under old key\n// result.prismaQueryOptions = module.default || module;\n// }\n// // Handle authConfigs (old vs new naming)\n// else if (key === \"authConfigs\") {\n// if (result.authConfigs) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"auth-configs\",\n// \"auth\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// result.authConfigs = module.default || module;\n// } else if (key === \"authConfigsNew\") {\n// if (result.authConfigs) {\n// throw Error(\n// `\\n Cannot use both ${fileName} and ${fileName.replace(\n// \"auth\",\n// \"auth-configs\"\n// )} at once, please choose only one name convention. \\n`\n// );\n// }\n// // Store new naming convention under old key\n// result.authConfigs = module.default || module;\n// }\n// // Handle other modules\n// else if (key === \"middlewares\" || key === \"router\") {\n// result[key] = module;\n// } else {\n// result[key as keyof typeof result] = module.default || module;\n// }\n// }\n// } catch (err: any) {\n// if (err.message.includes(\"Cannot use both\")) throw err;\n// console.error(err);\n// }\n// })\n// );\n\n// await Promise.all([\n// processSubdir(modelName, \"dtos\", result),\n// processSubdir(modelName, \"schemas\", result),\n// ]);\n\n// // Cache the result\n// prismaModelsModules[modelName] = result;\n\n// return result;\n// }\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels() {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\") ||\n trimmedLine.startsWith(\"/*\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine?.includes?.(\"@unique\");\n\n if (isUnique) {\n const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\n }\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine?.includes?.(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models?.includes?.(camelCase(cleanType || \"\"))\n ) {\n const enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n\n // && !content.includes?.(`model ${cleanType} {`)\n ) {\n continue;\n }\n\n if (!type?.includes?.(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n }\n}\n\ninitializePrismaModels();\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
@@ -37,9 +37,9 @@ export declare class BaseService<TModel extends Record<string, any> = any> {
|
|
|
37
37
|
[x: string]: any;
|
|
38
38
|
} ? W : any, queryOptions?: TOptions): Promise<TModel["findFirst"] extends (args: {
|
|
39
39
|
where: any;
|
|
40
|
-
}
|
|
40
|
+
}) => infer R ? R : TModel["findUnique"] extends (args: {
|
|
41
41
|
where: any;
|
|
42
|
-
}
|
|
42
|
+
}) => infer R2 ? R2 : any>;
|
|
43
43
|
updateOne<TOptions extends Omit<Parameters<TModel["update"]>[0], "where" | "data">>(filters: Parameters<TModel["update"]>[0] extends {
|
|
44
44
|
where: infer W;
|
|
45
45
|
[x: string]: any;
|