arkos 1.1.15-test → 1.1.17-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.
Files changed (77) hide show
  1. package/dist/cjs/modules/auth/auth.controller.js +18 -0
  2. package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
  3. package/dist/cjs/modules/auth/auth.router.js +22 -12
  4. package/dist/cjs/modules/auth/auth.router.js.map +1 -1
  5. package/dist/cjs/modules/auth/auth.service.js +7 -9
  6. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  7. package/dist/cjs/modules/base/base.controller.js +2 -2
  8. package/dist/cjs/modules/base/base.controller.js.map +1 -1
  9. package/dist/cjs/modules/base/base.middlewares.js +6 -4
  10. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  11. package/dist/cjs/modules/base/base.service.js +2 -2
  12. package/dist/cjs/modules/base/base.service.js.map +1 -1
  13. package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +31 -51
  14. package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
  15. package/dist/cjs/modules/file-uploader/file-uploader.router.js +3 -3
  16. package/dist/cjs/modules/file-uploader/file-uploader.router.js.map +1 -1
  17. package/dist/cjs/server.js +1 -1
  18. package/dist/cjs/server.js.map +1 -1
  19. package/dist/cjs/types/arkos-config.js.map +1 -1
  20. package/dist/cjs/utils/cli/build.js +3 -3
  21. package/dist/cjs/utils/cli/build.js.map +1 -1
  22. package/dist/cjs/utils/cli/dev.js +7 -38
  23. package/dist/cjs/utils/cli/dev.js.map +1 -1
  24. package/dist/cjs/utils/cli/index.js +36 -29
  25. package/dist/cjs/utils/cli/index.js.map +1 -1
  26. package/dist/cjs/utils/cli/start.js +9 -38
  27. package/dist/cjs/utils/cli/start.js.map +1 -1
  28. package/dist/cjs/utils/dotenv.helpers.js +1 -1
  29. package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
  30. package/dist/cjs/utils/helpers/models.helpers.js +2 -2
  31. package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
  32. package/dist/cjs/utils/validate-dto.js +1 -1
  33. package/dist/cjs/utils/validate-dto.js.map +1 -1
  34. package/dist/cjs/utils/validate-schema.js +1 -1
  35. package/dist/cjs/utils/validate-schema.js.map +1 -1
  36. package/dist/es2020/modules/auth/auth.controller.js +18 -0
  37. package/dist/es2020/modules/auth/auth.controller.js.map +1 -1
  38. package/dist/es2020/modules/auth/auth.router.js +22 -12
  39. package/dist/es2020/modules/auth/auth.router.js.map +1 -1
  40. package/dist/es2020/modules/auth/auth.service.js +7 -9
  41. package/dist/es2020/modules/auth/auth.service.js.map +1 -1
  42. package/dist/es2020/modules/base/base.controller.js +2 -2
  43. package/dist/es2020/modules/base/base.controller.js.map +1 -1
  44. package/dist/es2020/modules/base/base.middlewares.js +6 -4
  45. package/dist/es2020/modules/base/base.middlewares.js.map +1 -1
  46. package/dist/es2020/modules/base/base.service.js +2 -2
  47. package/dist/es2020/modules/base/base.service.js.map +1 -1
  48. package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js +31 -18
  49. package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
  50. package/dist/es2020/modules/file-uploader/file-uploader.router.js +3 -3
  51. package/dist/es2020/modules/file-uploader/file-uploader.router.js.map +1 -1
  52. package/dist/es2020/server.js +1 -1
  53. package/dist/es2020/server.js.map +1 -1
  54. package/dist/es2020/types/arkos-config.js.map +1 -1
  55. package/dist/es2020/utils/cli/build.js +3 -3
  56. package/dist/es2020/utils/cli/build.js.map +1 -1
  57. package/dist/es2020/utils/cli/dev.js +7 -5
  58. package/dist/es2020/utils/cli/dev.js.map +1 -1
  59. package/dist/es2020/utils/cli/index.js +35 -26
  60. package/dist/es2020/utils/cli/index.js.map +1 -1
  61. package/dist/es2020/utils/cli/start.js +9 -5
  62. package/dist/es2020/utils/cli/start.js.map +1 -1
  63. package/dist/es2020/utils/dotenv.helpers.js +1 -1
  64. package/dist/es2020/utils/dotenv.helpers.js.map +1 -1
  65. package/dist/es2020/utils/helpers/models.helpers.js +2 -2
  66. package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
  67. package/dist/es2020/utils/validate-dto.js +1 -1
  68. package/dist/es2020/utils/validate-dto.js.map +1 -1
  69. package/dist/es2020/utils/validate-schema.js +1 -1
  70. package/dist/es2020/utils/validate-schema.js.map +1 -1
  71. package/dist/types/modules/auth/auth.controller.d.ts +1 -0
  72. package/dist/types/modules/auth/auth.service.d.ts +2 -2
  73. package/dist/types/modules/base/base.middlewares.d.ts +2 -2
  74. package/dist/types/types/arkos-config.d.ts +2 -0
  75. package/dist/types/utils/cli/index.d.ts +5 -4
  76. package/dist/types/utils/helpers/models.helpers.d.ts +4 -4
  77. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":";;;;;;AAuYA,0CAOC;AA9YD,iFAIiD;AACjD,uEAI4C;AAC5C,4FAA6D;AAC7D,iFAAwD;AACxD,0DAAkC;AAClC,+EAAkF;AAClF,uEAAuE;AACvE,wEAA+C;AAS/C,MAAa,WAAW;IAmCtB,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;QACtE,IAAI,CAAC,8BAA8B,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ,EAAE,MAAM,CACzE,CAAC,GAA4B,EAAE,IAAI,EAAE,EAAE;YACrC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;YACtB,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAAE,CACH,CAAC;QACF,IAAI,CAAC,0BAA0B,GAAG,IAAI,CAAC,cAAc,EAAE,IAAI,EAAE,MAAM,CACjE,CAAC,GAA4B,EAA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CAAC;IACL,CAAC;IASD,KAAK,CAAC,UAAU,CACd,OAA4B;QAE5B,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;QAEnC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAC5C,MAAM,IAAI,mBAAQ,CAAC,wCAAwC,EAAE,GAAG,CAAC,CAAC;QACpE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAE9D,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,mBAAQ,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAAC;QACxD,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;QACnD,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACzB,CAAC;CACF;AAxWD,kCAwWC;AAOD,SAAgB,eAAe;IAC7B,MAAM,MAAM,GAAG,IAAA,0BAAS,GAAE,CAAC;IAC3B,MAAM,YAAY,GAAgC,EAAE,CAAC;IACrD,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 AppError from \"../error-handler/utils/app-error\";\nimport pluralize from \"pluralize\";\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 * by model-specific service classes.\n *\n * @class BaseService\n */\nexport class BaseService {\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 * Map of singular relation fields to include in queries\n * @public\n */\n singularRelationFieldToInclude: Record<string, boolean>;\n\n /**\n * Map of list relation fields to include in queries\n * @public\n */\n listRelationFieldToInclude: Record<string, boolean>;\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 this.singularRelationFieldToInclude = this.relationFields?.singular?.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n );\n this.listRelationFieldToInclude = this.relationFields?.list?.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n );\n }\n /**\n * Creates a single record in the database.\n *\n * @param {Record<string, any>} body - The data to create the record with.\n * @param {string} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<any>} The created record.\n */\n async createOne(\n body: Record<string, any>,\n queryOptions: string = \"{}\"\n ): Promise<any> {\n if (kebabCase(this.modelName) === \"user\" && body.password) {\n body.password = await authService.hashPassword(body.password);\n }\n\n const prisma = getPrismaInstance();\n\n const bodyWithRelationFieldsHandled = handleRelationFieldsInBody(\n body,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n return await prisma[this.modelName].create(\n deepmerge(\n {\n data: bodyWithRelationFieldsHandled,\n ...(JSON.parse(queryOptions || \"{}\").hasOwnProperty(\"select\")\n ? {\n select: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }\n : {\n include: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }),\n },\n JSON.parse(queryOptions || \"{}\")\n )\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Record<string, any>[]} body - An array of data to create records with.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the created data.\n * @throws {AppError} Throws an error if the data array is invalid or empty.\n */\n async createMany(\n body: Record<string, any>[]\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n if (!Array.isArray(body) || body.length === 0) {\n throw new AppError(\n \"Invalid or empty data array provided for creation.\",\n 400\n );\n }\n\n const [data, total] = await Promise.all([\n prisma[this.modelName].createMany({\n data: body,\n }),\n prisma[this.modelName].count(),\n ]);\n\n return { total, data };\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Record<string, any>} filters - The filters to apply to the query.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the found data.\n */\n async findMany(\n filters: Record<string, any>\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n const [data, total] = await Promise.all([\n prisma[this.modelName].findMany(\n \"select\" in filters\n ? deepmerge(\n { ...filters },\n {\n select: this.singularRelationFieldToInclude,\n }\n )\n : deepmerge(\n { ...filters },\n {\n include: this.singularRelationFieldToInclude,\n }\n )\n ),\n prisma[this.modelName].count({\n where: filters.where,\n }),\n ]);\n\n return { total, data };\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Record<string, any>} filters - The parameters to find the record by.\n * @param {string} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<any>} The found record.\n * @throws {AppError} Throws an error if the record is not found.\n */\n async findOne(\n filters: Record<string, any>,\n queryOptions: string = \"{}\"\n ): Promise<any> {\n const prisma = getPrismaInstance();\n\n const data = await prisma[this.modelName].findFirst(\n deepmerge(\n {\n where: { ...filters },\n ...(JSON.parse(queryOptions || \"{}\").hasOwnProperty(\"select\")\n ? {\n select: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }\n : {\n include: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }),\n },\n JSON.parse(queryOptions || \"{}\")\n )\n );\n\n if (!data && Object.keys(filters).length === 1 && \"id\" in filters)\n throw new AppError(\n `${pascalCase(String(this.modelName))} with ID ${filters.id} not found`,\n 404,\n {},\n \"not_found\"\n );\n else if (!data)\n throw new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n );\n\n return data;\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Record<string, any>} filters - The parameters to find the record by.\n * @param {Record<string, any>} body - The data to update the record with.\n * @param {string} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<any>} The updated record.\n * @throws {AppError} Throws an error if the record is not found.\n */\n async updateOne(\n filters: Record<string, any>,\n body: Record<string, any>,\n queryOptions: string = \"{}\"\n ): Promise<any> {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && body.password) {\n body.password = await authService.hashPassword(body.password);\n }\n\n const bodyWithRelationFieldsHandled = handleRelationFieldsInBody(body, {\n ...this.relationFields,\n });\n\n const data = await prisma[this.modelName].update(\n deepmerge(\n {\n where: { ...filters },\n data: bodyWithRelationFieldsHandled,\n ...(JSON.parse(queryOptions || \"{}\").hasOwnProperty(\"select\")\n ? {\n select: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }\n : {\n include: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }),\n },\n JSON.parse(queryOptions || \"{}\")\n )\n );\n\n if (!data && Object.keys(filters).length === 1 && \"id\" in filters)\n throw new AppError(\n `${pascalCase(String(this.modelName))} with ID ${filters.id} not found`,\n 404,\n {},\n \"not_found\"\n );\n else if (!data)\n throw new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n );\n\n return data;\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Record<string, any>} filters - The filters to identify records to update.\n * @param {Record<string, any>} body - The data to update the records with.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the updated data.\n * @throws {AppError} Throws an error if no records match the filters.\n */\n async updateMany(\n filters: Record<string, any>,\n body: Record<string, any>\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n if (!filters || typeof filters !== \"object\") {\n throw new AppError(\"Invalid filters provided for udpate many.\", 400);\n }\n\n const data = await prisma[this.modelName].updateMany({\n ...filters,\n data: body,\n });\n\n if (!data || data.count === 0) {\n throw new AppError(\n `${pluralize(pascalCase(String(this.modelName)))} not found`,\n 404\n );\n }\n\n const total = await prisma[this.modelName].count();\n return { total, data };\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Record<string, any>} params - The parameters to find the record by.\n * @returns {Promise<any>} The deleted record.\n */\n async deleteOne(params: Record<string, any>): Promise<any> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].delete({\n where: {\n ...params,\n id: String(params.id),\n },\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Record<string, any>} filter - The filter to identify records to delete.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the deleted data.\n * @throws {AppError} Throws an error if no records match the filter.\n */\n async deleteMany(\n filters: Record<string, any>\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n if (!filters || typeof filters !== \"object\") {\n throw new AppError(\"Invalid filters provided for deletion.\", 400);\n }\n\n const data = await prisma[this.modelName].deleteMany(filters);\n\n if (!data || data.count === 0) {\n throw new AppError(`No records found to delete`, 404);\n }\n\n const total = await prisma[this.modelName].count();\n return { total, data };\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> {\n const models = getModels();\n const baseServices: Record<string, BaseService> = {};\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":";;;;;;AA2YA,0CAOC;AAlZD,iFAIiD;AACjD,uEAI4C;AAC5C,4FAA6D;AAC7D,iFAAwD;AACxD,0DAAkC;AAClC,+EAAkF;AAClF,uEAAuE;AACvE,wEAA+C;AAS/C,MAAa,WAAW;IAmCtB,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;QACtE,IAAI,CAAC,8BAA8B,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ,EAAE,MAAM,CACzE,CAAC,GAA4B,EAAE,IAAI,EAAE,EAAE;YACrC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;YACtB,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAAE,CACH,CAAC;QACF,IAAI,CAAC,0BAA0B,GAAG,IAAI,CAAC,cAAc,EAAE,IAAI,EAAE,MAAM,CACjE,CAAC,GAA4B,EAAE,IAAI,EAAE,EAAE;YACrC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;YACtB,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAAE,CACH,CAAC;IACJ,CAAC;IAQD,KAAK,CAAC,SAAS,CACb,IAAyB,EACzB,eAAuB,IAAI;QAE3B,IAAI,IAAA,+BAAS,EAAC,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC1D,IAAI,CAAC,QAA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AO,CAAC,CAAC;QAE9D,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,mBAAQ,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAAC;QACxD,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;QACnD,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACzB,CAAC;CACF;AA5WD,kCA4WC;AAOD,SAAgB,eAAe;IAC7B,MAAM,MAAM,GAAG,IAAA,0BAAS,GAAE,CAAC;IAC3B,MAAM,YAAY,GAAgC,EAAE,CAAC;IACrD,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 AppError from \"../error-handler/utils/app-error\";\nimport pluralize from \"pluralize\";\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 * by model-specific service classes.\n *\n * @class BaseService\n */\nexport class BaseService {\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 * Map of singular relation fields to include in queries\n * @public\n */\n singularRelationFieldToInclude: Record<string, boolean>;\n\n /**\n * Map of list relation fields to include in queries\n * @public\n */\n listRelationFieldToInclude: Record<string, boolean>;\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 this.singularRelationFieldToInclude = this.relationFields?.singular?.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n );\n this.listRelationFieldToInclude = this.relationFields?.list?.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n );\n }\n /**\n * Creates a single record in the database.\n *\n * @param {Record<string, any>} body - The data to create the record with.\n * @param {string} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<any>} The created record.\n */\n async createOne(\n body: Record<string, any>,\n queryOptions: string = \"{}\"\n ): Promise<any> {\n if (kebabCase(this.modelName) === \"user\" && body.password) {\n body.password = await authService.hashPassword(body.password);\n }\n\n const prisma = getPrismaInstance();\n\n const bodyWithRelationFieldsHandled = handleRelationFieldsInBody(\n body,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n return await prisma[this.modelName].create(\n deepmerge(\n {\n data: bodyWithRelationFieldsHandled,\n ...(JSON.parse(queryOptions || \"{}\").hasOwnProperty(\"select\")\n ? {\n select: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }\n : {\n include: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }),\n },\n JSON.parse(queryOptions || \"{}\")\n )\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Record<string, any>[]} body - An array of data to create records with.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the created data.\n * @throws {AppError} Throws an error if the data array is invalid or empty.\n */\n async createMany(\n body: Record<string, any>[]\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n if (!Array.isArray(body) || body.length === 0) {\n throw new AppError(\n \"Invalid or empty data array provided for creation.\",\n 400\n );\n }\n\n const [data, total] = await Promise.all([\n prisma[this.modelName].createMany({\n data: body,\n }),\n prisma[this.modelName].count(),\n ]);\n\n return { total, data };\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Record<string, any>} filters - The filters to apply to the query.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the found data.\n */\n async findMany(\n filters: Record<string, any>\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n const [data, total] = await Promise.all([\n prisma[this.modelName].findMany(\n \"select\" in filters\n ? deepmerge(\n { ...filters },\n {\n select: this.singularRelationFieldToInclude,\n }\n )\n : deepmerge(\n { ...filters },\n {\n include: this.singularRelationFieldToInclude,\n }\n )\n ),\n prisma[this.modelName].count({\n where: filters.where,\n }),\n ]);\n\n return { total, data };\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Record<string, any>} filters - The parameters to find the record by.\n * @param {string} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<any>} The found record.\n * @throws {AppError} Throws an error if the record is not found.\n */\n async findOne(\n filters: Record<string, any>,\n queryOptions: string = \"{}\"\n ): Promise<any> {\n const prisma = getPrismaInstance();\n\n const data = await prisma[this.modelName].findFirst(\n deepmerge(\n {\n where: { ...filters },\n ...(JSON.parse(queryOptions || \"{}\").hasOwnProperty(\"select\")\n ? {\n select: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }\n : {\n include: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }),\n },\n JSON.parse(queryOptions || \"{}\")\n )\n );\n\n if (!data && Object.keys(filters).length === 1 && \"id\" in filters)\n throw new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n filters?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n );\n else if (!data)\n throw new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n );\n\n return data;\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Record<string, any>} filters - The parameters to find the record by.\n * @param {Record<string, any>} body - The data to update the record with.\n * @param {string} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<any>} The updated record.\n * @throws {AppError} Throws an error if the record is not found.\n */\n async updateOne(\n filters: Record<string, any>,\n body: Record<string, any>,\n queryOptions: string = \"{}\"\n ): Promise<any> {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && body.password) {\n body.password = await authService.hashPassword(body.password);\n }\n\n const bodyWithRelationFieldsHandled = handleRelationFieldsInBody(body, {\n ...this.relationFields,\n });\n\n const data = await prisma[this.modelName].update(\n deepmerge(\n {\n where: { ...filters },\n data: bodyWithRelationFieldsHandled,\n ...(JSON.parse(queryOptions || \"{}\").hasOwnProperty(\"select\")\n ? {\n select: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }\n : {\n include: {\n ...this.singularRelationFieldToInclude,\n ...this.listRelationFieldToInclude,\n },\n }),\n },\n JSON.parse(queryOptions || \"{}\")\n )\n );\n\n if (!data && Object.keys(filters).length === 1 && \"id\" in filters)\n throw new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n filters?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n );\n else if (!data)\n throw new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n );\n\n return data;\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Record<string, any>} filters - The filters to identify records to update.\n * @param {Record<string, any>} body - The data to update the records with.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the updated data.\n * @throws {AppError} Throws an error if no records match the filters.\n */\n async updateMany(\n filters: Record<string, any>,\n body: Record<string, any>\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n if (!filters || typeof filters !== \"object\") {\n throw new AppError(\"Invalid filters provided for udpate many.\", 400);\n }\n\n const data = await prisma[this.modelName].updateMany({\n ...filters,\n data: body,\n });\n\n if (!data || data.count === 0) {\n throw new AppError(\n `${pluralize(pascalCase(String(this.modelName)))} not found`,\n 404\n );\n }\n\n const total = await prisma[this.modelName].count();\n return { total, data };\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Record<string, any>} params - The parameters to find the record by.\n * @returns {Promise<any>} The deleted record.\n */\n async deleteOne(params: Record<string, any>): Promise<any> {\n const prisma = getPrismaInstance();\n\n return await prisma[this.modelName].delete({\n where: {\n ...params,\n id: String(params.id),\n },\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Record<string, any>} filter - The filter to identify records to delete.\n * @returns {Promise<{ total: number; data: any }>} The result containing the total count and the deleted data.\n * @throws {AppError} Throws an error if no records match the filter.\n */\n async deleteMany(\n filters: Record<string, any>\n ): Promise<{ total: number; data: any }> {\n const prisma = getPrismaInstance();\n\n if (!filters || typeof filters !== \"object\") {\n throw new AppError(\"Invalid filters provided for deletion.\", 400);\n }\n\n const data = await prisma[this.modelName].deleteMany(filters);\n\n if (!data || data.count === 0) {\n throw new AppError(`No records found to delete`, 404);\n }\n\n const total = await prisma[this.modelName].count();\n return { total, data };\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> {\n const models = getModels();\n const baseServices: Record<string, BaseService> = {};\n models.forEach((model) => {\n baseServices[`${camelCase(model)}`] = new BaseService(model);\n });\n return baseServices;\n}\n"]}
@@ -1,43 +1,10 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
4
  };
38
5
  Object.defineProperty(exports, "__esModule", { value: true });
39
6
  exports.setupRouters = setupRouters;
40
- const pluralize_1 = __importStar(require("pluralize"));
7
+ const pluralize_1 = require("pluralize");
41
8
  const utils_1 = require("../../../../exports/utils");
42
9
  const models_helpers_1 = require("../../../../utils/helpers/models.helpers");
43
10
  const auth_service_1 = __importDefault(require("../../../auth/auth.service"));
@@ -48,7 +15,7 @@ function setupRouters(models, router, arkosConfigs) {
48
15
  const modelNameInKebab = (0, utils_1.kebabCase)(model);
49
16
  const modelModules = await (0, models_helpers_1.importPrismaModelModules)(modelNameInKebab);
50
17
  const { middlewares, authConfigs, prismaQueryOptions, router: customRouterModule, dtos, schemas, } = modelModules;
51
- const routeName = pluralize_1.default.plural(modelNameInKebab);
18
+ const routeName = (0, pluralize_1.plural)(modelNameInKebab);
52
19
  const controller = new base_controller_1.BaseController(model);
53
20
  const routerConfig = customRouterModule?.config;
54
21
  const disableConfig = routerConfig?.disable || {};
@@ -75,68 +42,81 @@ function setupRouters(models, router, arkosConfigs) {
75
42
  };
76
43
  if (!isEndpointDisabled("createOne") &&
77
44
  !hasCustomImplementation(`/${routeName}`, "post")) {
78
- router.post(`/${routeName}`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Create", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("create")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "createOne"), middlewares?.beforeCreateOne ?? controller.createOne, middlewares?.beforeCreateOne
45
+ router.post(`/${routeName}`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Create", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("create")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "createOne"), middlewares?.beforeCreateOne || controller.createOne, middlewares?.beforeCreateOne
79
46
  ? controller.createOne
80
- : middlewares?.afterCreateOne ?? base_middlewares_1.sendResponse, middlewares?.beforeCreateOne && middlewares?.afterCreateOne
47
+ : middlewares?.afterCreateOne || base_middlewares_1.sendResponse, middlewares?.beforeCreateOne && middlewares?.afterCreateOne
81
48
  ? middlewares?.afterCreateOne
82
49
  : base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
83
50
  }
84
51
  if (!isEndpointDisabled("findMany") &&
85
52
  !hasCustomImplementation(`/${routeName}`, "get")) {
86
- router.get(`/${routeName}`, auth_service_1.default.handleAuthenticationControl("View", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("View", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "findMany"), middlewares?.beforeFindMany ?? controller.findMany, middlewares?.beforeFindMany
53
+ router.get(`/${routeName}`, auth_service_1.default.handleAuthenticationControl("View", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("View", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "findMany"), middlewares?.beforeFindMany || controller.findMany, middlewares?.beforeFindMany
87
54
  ? controller.findMany
88
- : middlewares?.afterFindMany ?? base_middlewares_1.sendResponse, middlewares?.beforeFindMany && middlewares?.afterFindMany
55
+ : middlewares?.afterFindMany || base_middlewares_1.sendResponse, middlewares?.beforeFindMany && middlewares?.afterFindMany
89
56
  ? middlewares?.afterFindMany
90
57
  : base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
91
58
  }
92
59
  if (!isEndpointDisabled("createMany") &&
93
60
  !hasCustomImplementation(`/${routeName}/many`, "post")) {
94
- router.post(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Create", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("createMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "createMany"), middlewares?.beforeCreateMany ?? controller.createMany, middlewares?.beforeCreateMany
61
+ router.post(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Create", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("createMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "createMany"), middlewares?.beforeCreateMany || controller.createMany, middlewares?.beforeCreateMany
95
62
  ? controller.createMany
96
- : middlewares?.afterCreateMany ?? base_middlewares_1.sendResponse, middlewares?.beforeCreateMany && middlewares?.afterCreateMany
63
+ : middlewares?.afterCreateMany || base_middlewares_1.sendResponse, middlewares?.beforeCreateMany && middlewares?.afterCreateMany
97
64
  ? middlewares?.afterCreateMany
98
65
  : base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
99
66
  }
100
67
  if (!isEndpointDisabled("updateMany") &&
101
68
  !hasCustomImplementation(`/${routeName}/many`, "patch")) {
102
- router.patch(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Update", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("updateMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "updateMany"), middlewares?.beforeUpdateMany ?? controller.updateMany, middlewares?.beforeUpdateMany
69
+ router.patch(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Update", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("updateMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "updateMany"), middlewares?.beforeUpdateMany || controller.updateMany, middlewares?.beforeUpdateMany
103
70
  ? controller.updateMany
104
- : middlewares?.afterUpdateMany ?? base_middlewares_1.sendResponse, middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany
71
+ : middlewares?.afterUpdateMany || base_middlewares_1.sendResponse, middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany
105
72
  ? middlewares?.afterUpdateMany
106
73
  : base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
107
74
  }
108
75
  if (!isEndpointDisabled("deleteMany") &&
109
76
  !hasCustomImplementation(`/${routeName}/many`, "delete")) {
110
- router.delete(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Delete", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("deleteMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "deleteMany"), middlewares?.beforeDeleteMany ?? controller.deleteMany, middlewares?.beforeDeleteMany
77
+ router.delete(`/${routeName}/many`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Delete", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("deleteMany")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "deleteMany"), middlewares?.beforeDeleteMany || controller.deleteMany, middlewares?.beforeDeleteMany
111
78
  ? controller.deleteMany
112
- : middlewares?.afterDeleteMany ?? base_middlewares_1.sendResponse, middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany
79
+ : middlewares?.afterDeleteMany || base_middlewares_1.sendResponse, middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany
113
80
  ? middlewares?.afterDeleteMany
114
81
  : base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
115
82
  }
116
83
  if (!isEndpointDisabled("findOne") &&
117
84
  !hasCustomImplementation(`/${routeName}/:id`, "get")) {
118
- router.get(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("View", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("View", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("findOne")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "findOne"), middlewares?.beforeFindOne ?? controller.findOne, middlewares?.beforeFindOne
85
+ router.get(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("View", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("View", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("findOne")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "findOne"), middlewares?.beforeFindOne || controller.findOne, middlewares?.beforeFindOne
119
86
  ? controller.findOne
120
- : middlewares?.afterFindOne ?? base_middlewares_1.sendResponse, middlewares?.beforeFindOne && middlewares?.afterFindOne
87
+ : middlewares?.afterFindOne || base_middlewares_1.sendResponse, middlewares?.beforeFindOne && middlewares?.afterFindOne
121
88
  ? middlewares?.afterFindOne
122
89
  : base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
123
90
  }
124
91
  if (!isEndpointDisabled("updateOne") &&
125
92
  !hasCustomImplementation(`/${routeName}/:id`, "patch")) {
126
- router.patch(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Update", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("update")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "updateOne"), middlewares?.beforeUpdateOne ?? controller.updateOne, middlewares?.beforeUpdateOne
93
+ router.patch(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("Update", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Update", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("update")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "updateOne"), middlewares?.beforeUpdateOne || controller.updateOne, middlewares?.beforeUpdateOne
127
94
  ? controller.updateOne
128
- : middlewares?.afterUpdateOne ?? base_middlewares_1.sendResponse, middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne
95
+ : middlewares?.afterUpdateOne || base_middlewares_1.sendResponse, middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne
129
96
  ? middlewares?.afterUpdateOne
130
97
  : base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
131
98
  }
132
99
  if (!isEndpointDisabled("deleteOne") &&
133
100
  !hasCustomImplementation(`/${routeName}/:id`, "delete")) {
134
- router.delete(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Delete", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("delete")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "deleteOne"), middlewares?.beforeDeleteOne ?? controller.deleteOne, middlewares?.beforeDeleteOne
101
+ router.delete(`/${routeName}/:id`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs?.authenticationControl), auth_service_1.default.handleAccessControl("Delete", (0, utils_1.kebabCase)((0, pluralize_1.singular)(modelNameInKebab)), authConfigs?.accessControl || {}), (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("delete")), (0, base_middlewares_1.addPrismaQueryOptionsToRequestQuery)(prismaQueryOptions, "deleteOne"), middlewares?.beforeDeleteOne || controller.deleteOne, middlewares?.beforeDeleteOne
135
102
  ? controller.deleteOne
136
- : middlewares?.afterDeleteOne ?? base_middlewares_1.sendResponse, middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne
103
+ : middlewares?.afterDeleteOne || base_middlewares_1.sendResponse, middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne
137
104
  ? middlewares?.afterDeleteOne
138
105
  : base_middlewares_1.sendResponse, base_middlewares_1.sendResponse);
139
106
  }
107
+ if (customRouterModule?.default && !customRouterModule?.config?.disable) {
108
+ customRouter.stack.forEach((layer) => {
109
+ if (layer.route) {
110
+ const route = layer.route;
111
+ const path = route.path;
112
+ route.stack.forEach((routeLayer) => {
113
+ const method = routeLayer.method.toLowerCase();
114
+ const handlers = route.stack.map((routeStack) => routeStack.handle);
115
+ router[method](`/${routeName}/${path}`, ...handlers);
116
+ });
117
+ }
118
+ });
119
+ }
140
120
  });
141
121
  }
142
122
  //# sourceMappingURL=base.router.helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,oCA6UC;AA3VD,uDAAgD;AAEhD,qDAAsD;AAGtD,6EAAoF;AACpF,8EAAqD;AACrD,2DAAuD;AACvD,6DAIgC;AAEhC,SAAgB,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,IAAA,iBAAS,EAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB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7C,WAAW,CACZ,EACD,WAAW,EAAE,eAAe,IAAI,UAAU,CAAC,SAAS,EACpD,WAAW,EAAE,eAAe;gBAC1B,CAAC,CAAC,UAAU,CAAC,SAAS;gBACtB,CAAC,CAAC,WAAW,EAAE,cAAc,IAAI,+BAAY,EAC/C,WAAW,EAAE,eAAe,IAAI,WAAW,EAAE,cAAc;gBACzD,CAAC,CAAC,WAAW,EAAE,cAAc;gBAC7B,CAAC,CAAC,+BAAY,EAChB,+BAAY,CACb,CAAC;QACJ,CAAC;IACH,CAAC,CAAC,CAAC;AASL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport pluralize, { singular } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequestQuery,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = pluralize.plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n layer.path === `/api/${path}` &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // Create individual routes instead of chaining\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne ?? controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne ?? sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany ?? controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany ?? sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany ?? controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany ?? sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany ?? controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany ?? sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany ?? controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany ?? sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne ?? controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne ?? sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne ?? controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne ?? sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne ?? controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne ?? sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n });\n\n // // If the custom router has its own routes, add them\n // if (customRouterModule?.default) {\n // customRouter.stack.forEach((stack) => {\n // const { method, path, handle } = stack;\n // (router as any)[method.toLowerCase()](path, handle);\n // });\n // }\n}\n"]}
1
+ {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;AAeA,oCAuVC;AArWD,yCAA6C;AAE7C,qDAAsD;AAGtD,6EAAoF;AACpF,8EAAqD;AACrD,2DAAuD;AACvD,6DAIgC;AAEhC,SAAgB,YAAY,CAC1B,MAAgB,EAChB,MAAc,EACd,YAAyB;IAEzB,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAChC,MAAM,gBAAgB,GAAG,IAAA,iBAAS,EAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,gBAAgB,CAAC,CAAC;QACtE,MAAM,EACJ,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,IAAI,EACJ,OAAO,GACR,GAAG,YAAY,CAAC;QAEjB,MAAM,SAAS,GAAG,IAAA,kBAAM,EAAC,gBAAgB,CAAC,CAAC;QAC3C,MAAM,UAAU,GAAG,IAAI,gCAAc,CAAC,KAAK,CAAC,CAAC;QAG7C,MAAM,YAAY,GAAiB,kBAAkB,EAAE,MAAM,CAAC;QAC9D,MAAM,aAAa,GAAG,YAAY,EAAE,OAAO,IAAI,EAAE,CAAC;QAClD,MAAM,oBAAoB,GAAG,aAAa,KAAK,IAAI,CAAC;QAGpD,MAAM,YAAY,GAAI,kBAAkB,EAAE,OAAkB,IAAI,EAAE,CAAC;QACnE,MAAM,uBAAuB,GAAG,CAAC,IAAY,EAAE,MAAc,EAAE,EAAE;YAC/D,OAAO,YAAY,CAAC,KAAK,EAAE,IAAI,CAC7B,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,EAAE;gBAC7B,KAAK,CAAC,MAAM,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,CACtD,CAAC;QACJ,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,GAAG,UAAU,CAAC,MAAM,CAAC,WAAW,EAAS,CAAC;wBAGtD,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;wBAGnE,MAAc,CAAC,MAAM,CAAC,CAAC,IAAI,SAAS,IAAI,IAAI,EAAE,EAAE,GAAG,QAAQ,CAAC,CAAC;oBAChE,CAAC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { singular, plural } from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport { RouterEndpoint } from \"../../../../types/router-config\";\nimport { importPrismaModelModules } from \"../../../../utils/helpers/models.helpers\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequestQuery,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\n\nexport function setupRouters(\n models: string[],\n router: Router,\n arkosConfigs: ArkosConfig\n) {\n return models.map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = await importPrismaModelModules(modelNameInKebab);\n const {\n middlewares,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n // Check for router customization/disabling\n const routerConfig: RouterConfig = customRouterModule?.config;\n const disableConfig = routerConfig?.disable || {};\n const isCompletelyDisabled = disableConfig === true;\n\n // Check if custom implementation exists\n const customRouter = (customRouterModule?.default as Router) || {};\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter.stack?.some(\n (layer) =>\n layer.path === `/api/${path}` &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n // Helper to determine if an endpoint should be disabled\n const isEndpointDisabled = (endpoint: RouterEndpoint): boolean => {\n if (isCompletelyDisabled) return true;\n return typeof disableConfig === \"object\" && !!disableConfig[endpoint];\n };\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (\n key: keyof typeof dtos | keyof typeof schemas\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // POST /{routeName} - Create One\n if (\n !isEndpointDisabled(\"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n middlewares?.beforeCreateOne || controller.createOne,\n middlewares?.beforeCreateOne\n ? controller.createOne\n : middlewares?.afterCreateOne || sendResponse,\n middlewares?.beforeCreateOne && middlewares?.afterCreateOne\n ? middlewares?.afterCreateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(\"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n middlewares?.beforeFindMany || controller.findMany,\n middlewares?.beforeFindMany\n ? controller.findMany\n : middlewares?.afterFindMany || sendResponse,\n middlewares?.beforeFindMany && middlewares?.afterFindMany\n ? middlewares?.afterFindMany\n : sendResponse,\n sendResponse\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(\"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"createMany\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n middlewares?.beforeCreateMany || controller.createMany,\n middlewares?.beforeCreateMany\n ? controller.createMany\n : middlewares?.afterCreateMany || sendResponse,\n middlewares?.beforeCreateMany && middlewares?.afterCreateMany\n ? middlewares?.afterCreateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(\"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMany\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n middlewares?.beforeUpdateMany || controller.updateMany,\n middlewares?.beforeUpdateMany\n ? controller.updateMany\n : middlewares?.afterUpdateMany || sendResponse,\n middlewares?.beforeUpdateMany && middlewares?.afterUpdateMany\n ? middlewares?.afterUpdateMany\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(\"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"deleteMany\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n middlewares?.beforeDeleteMany || controller.deleteMany,\n middlewares?.beforeDeleteMany\n ? controller.deleteMany\n : middlewares?.afterDeleteMany || sendResponse,\n middlewares?.beforeDeleteMany && middlewares?.afterDeleteMany\n ? middlewares?.afterDeleteMany\n : sendResponse,\n sendResponse\n );\n }\n\n // GET /{routeName}/:id - Find One\n if (\n !isEndpointDisabled(\"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"findOne\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n middlewares?.beforeFindOne || controller.findOne,\n middlewares?.beforeFindOne\n ? controller.findOne\n : middlewares?.afterFindOne || sendResponse,\n middlewares?.beforeFindOne && middlewares?.afterFindOne\n ? middlewares?.afterFindOne\n : sendResponse,\n sendResponse\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(\"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n middlewares?.beforeUpdateOne || controller.updateOne,\n middlewares?.beforeUpdateOne\n ? controller.updateOne\n : middlewares?.afterUpdateOne || sendResponse,\n middlewares?.beforeUpdateOne && middlewares?.afterUpdateOne\n ? middlewares?.afterUpdateOne\n : sendResponse,\n sendResponse\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(\"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs?.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n kebabCase(singular(modelNameInKebab)),\n authConfigs?.accessControl || {}\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"delete\")\n ),\n addPrismaQueryOptionsToRequestQuery<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n middlewares?.beforeDeleteOne || controller.deleteOne,\n middlewares?.beforeDeleteOne\n ? controller.deleteOne\n : middlewares?.afterDeleteOne || sendResponse,\n middlewares?.beforeDeleteOne && middlewares?.afterDeleteOne\n ? middlewares?.afterDeleteOne\n : sendResponse,\n sendResponse\n );\n }\n\n // If the custom router has its own routes, add them\n if (customRouterModule?.default && !customRouterModule?.config?.disable) {\n customRouter.stack.forEach((layer) => {\n if (layer.route) {\n const route = layer.route;\n const path = route.path;\n\n route.stack.forEach((routeLayer) => {\n const method = routeLayer.method.toLowerCase() as any;\n\n // Get all middleware handlers for this route\n const handlers = route.stack.map((routeStack) => routeStack.handle);\n\n // Apply all middleware handlers to the matching route method\n (router as any)[method](`/${routeName}/${path}`, ...handlers);\n });\n }\n });\n }\n });\n}\n"]}
@@ -23,7 +23,7 @@ async function getFileUploaderRouter({ fileUpload }) {
23
23
  basePathname = "/" + basePathname;
24
24
  if (!basePathname.endsWith("/"))
25
25
  basePathname = basePathname + "/";
26
- router.use(basePathname, auth_service_1.default.handleAuthenticationControl("view", authConfigs), auth_service_1.default.handleAccessControl("view", "file-upload", authConfigs), express_2.default.static(path_1.default.resolve(process.cwd(), fileUpload?.baseUploadDir || "uploads"), (0, deepmerge_helper_1.default)({
26
+ router.use(basePathname, auth_service_1.default.handleAuthenticationControl("View", authConfigs), auth_service_1.default.handleAccessControl("View", "file-upload", authConfigs), express_2.default.static(path_1.default.resolve(process.cwd(), fileUpload?.baseUploadDir || "uploads"), (0, deepmerge_helper_1.default)({
27
27
  maxAge: "1y",
28
28
  etag: true,
29
29
  lastModified: true,
@@ -32,8 +32,8 @@ async function getFileUploaderRouter({ fileUpload }) {
32
32
  index: false,
33
33
  cacheControl: true,
34
34
  }, fileUpload?.expressStaticOptions || {})));
35
- router.post(`${basePathname}:fileType`, auth_service_1.default.handleAuthenticationControl("create", authConfigs), auth_service_1.default.handleAccessControl("create", "file-upload", authConfigs), file_uploader_controller_1.uploadFile);
36
- router.delete(`${basePathname}:fileType/:fileName`, auth_service_1.default.handleAuthenticationControl("delete", authConfigs), auth_service_1.default.handleAccessControl("create", "file-upload", authConfigs), file_uploader_controller_1.deleteFile);
35
+ router.post(`${basePathname}:fileType`, auth_service_1.default.handleAuthenticationControl("Create", authConfigs), auth_service_1.default.handleAccessControl("Create", "file-upload", authConfigs), file_uploader_controller_1.uploadFile);
36
+ router.delete(`${basePathname}:fileType/:fileName`, auth_service_1.default.handleAuthenticationControl("Delete", authConfigs), auth_service_1.default.handleAccessControl("Create", "file-upload", authConfigs), file_uploader_controller_1.deleteFile);
37
37
  return router;
38
38
  }
39
39
  //# sourceMappingURL=file-uploader.router.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"file-uploader.router.js","sourceRoot":"","sources":["../../../../src/modules/file-uploader/file-uploader.router.ts"],"names":[],"mappings":";;;;;AAWA,sDAiDC;AA5DD,qCAAiC;AACjC,uEAA8E;AAC9E,wEAA+C;AAC/C,yEAAoE;AAEpE,gDAAwB;AACxB,sDAA8B;AAC9B,4FAA6D;AAE7D,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;AAEzB,KAAK,UAAU,qBAAqB,CAAC,EAAE,UAAU,EAAe;IACrE,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,aAAa,CAAC,CAAC;IACnE,IAAI,EAAE,WAAW,GAAG,EAAE,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC;IAEhD,IAAI,YAAY,EAAE,CAAC;QACjB,CAAC,EAAE,WAAW,GAAG,EAAE,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,YAAY,CAAC,CAAC;IAC1D,CAAC;IAED,IAAI,YAAY,GAAG,UAAU,EAAE,SAAS,IAAI,eAAe,CAAC;IAE5D,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,YAAY,GAAG,GAAG,GAAG,YAAY,CAAC;IACrE,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,YAAY,GAAG,YAAY,GAAG,GAAG,CAAC;IAEnE,MAAM,CAAC,GAAG,CACR,YAAY,EACZ,sBAAW,CAAC,2BAA2B,CAAC,MAAM,EAAE,WAAW,CAAC,EAC5D,sBAAW,CAAC,mBAAmB,CAAC,MAAM,EAAE,aAAa,EAAE,WAAW,CAAC,EACnE,iBAAO,CAAC,MAAM,CACZ,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,UAAU,EAAE,aAAa,IAAI,SAAS,CAAC,EACnE,IAAA,0BAAS,EACP;QACE,MAAM,EAAE,IAAI;QACZ,IAAI,EAAE,IAAI;QACV,YAAY,EAAE,IAAI;QAClB,QAAQ,EAAE,QAAQ;QAClB,WAAW,EAAE,IAAI;QACjB,KAAK,EAAE,KAAK;QACZ,YAAY,EAAE,IAAI;KACnB,EACD,UAAU,EAAE,oBAAoB,IAAI,EAAE,CACvC,CACF,CACF,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,GAAG,YAAY,WAAW,EAC1B,sBAAW,CAAC,2BAA2B,CAAC,QAAQ,EAAE,WAAW,CAAC,EAC9D,sBAAW,CAAC,mBAAmB,CAAC,QAAQ,EAAE,aAAa,EAAE,WAAW,CAAC,EACrE,qCAAU,CACX,CAAC;IAEF,MAAM,CAAC,MAAM,CACX,GAAG,YAAY,qBAAqB,EACpC,sBAAW,CAAC,2BAA2B,CAAC,QAAQ,EAAE,WAAW,CAAC,EAC9D,sBAAW,CAAC,mBAAmB,CAAC,QAAQ,EAAE,aAAa,EAAE,WAAW,CAAC,EACrE,qCAAU,CACX,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport authService from \"../auth/auth.service\";\nimport { deleteFile, uploadFile } from \"./file-uploader.controller\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport path from \"path\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\n\nconst router: Router = Router();\n\nexport async function getFileUploaderRouter({ fileUpload }: ArkosConfig) {\n const modelModules = await importPrismaModelModules(\"file-upload\");\n let { middlewares = {}, authConfigs = {} } = {};\n\n if (modelModules) {\n ({ middlewares = {}, authConfigs = {} } = modelModules);\n }\n\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n router.use(\n basePathname,\n authService.handleAuthenticationControl(\"view\", authConfigs),\n authService.handleAccessControl(\"view\", \"file-upload\", authConfigs),\n express.static(\n path.resolve(process.cwd(), fileUpload?.baseUploadDir || \"uploads\"),\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStaticOptions || {}\n )\n )\n );\n\n router.post(\n `${basePathname}:fileType`,\n authService.handleAuthenticationControl(\"create\", authConfigs),\n authService.handleAccessControl(\"create\", \"file-upload\", authConfigs),\n uploadFile\n );\n\n router.delete(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\"delete\", authConfigs),\n authService.handleAccessControl(\"create\", \"file-upload\", authConfigs),\n deleteFile\n );\n\n return router;\n}\n"]}
1
+ {"version":3,"file":"file-uploader.router.js","sourceRoot":"","sources":["../../../../src/modules/file-uploader/file-uploader.router.ts"],"names":[],"mappings":";;;;;AAWA,sDAiDC;AA5DD,qCAAiC;AACjC,uEAA8E;AAC9E,wEAA+C;AAC/C,yEAAoE;AAEpE,gDAAwB;AACxB,sDAA8B;AAC9B,4FAA6D;AAE7D,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;AAEzB,KAAK,UAAU,qBAAqB,CAAC,EAAE,UAAU,EAAe;IACrE,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,aAAa,CAAC,CAAC;IACnE,IAAI,EAAE,WAAW,GAAG,EAAE,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC;IAEhD,IAAI,YAAY,EAAE,CAAC;QACjB,CAAC,EAAE,WAAW,GAAG,EAAE,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,YAAY,CAAC,CAAC;IAC1D,CAAC;IAED,IAAI,YAAY,GAAG,UAAU,EAAE,SAAS,IAAI,eAAe,CAAC;IAE5D,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,YAAY,GAAG,GAAG,GAAG,YAAY,CAAC;IACrE,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,YAAY,GAAG,YAAY,GAAG,GAAG,CAAC;IAEnE,MAAM,CAAC,GAAG,CACR,YAAY,EACZ,sBAAW,CAAC,2BAA2B,CAAC,MAAM,EAAE,WAAW,CAAC,EAC5D,sBAAW,CAAC,mBAAmB,CAAC,MAAM,EAAE,aAAa,EAAE,WAAW,CAAC,EACnE,iBAAO,CAAC,MAAM,CACZ,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,UAAU,EAAE,aAAa,IAAI,SAAS,CAAC,EACnE,IAAA,0BAAS,EACP;QACE,MAAM,EAAE,IAAI;QACZ,IAAI,EAAE,IAAI;QACV,YAAY,EAAE,IAAI;QAClB,QAAQ,EAAE,QAAQ;QAClB,WAAW,EAAE,IAAI;QACjB,KAAK,EAAE,KAAK;QACZ,YAAY,EAAE,IAAI;KACnB,EACD,UAAU,EAAE,oBAAoB,IAAI,EAAE,CACvC,CACF,CACF,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,GAAG,YAAY,WAAW,EAC1B,sBAAW,CAAC,2BAA2B,CAAC,QAAQ,EAAE,WAAW,CAAC,EAC9D,sBAAW,CAAC,mBAAmB,CAAC,QAAQ,EAAE,aAAa,EAAE,WAAW,CAAC,EACrE,qCAAU,CACX,CAAC;IAEF,MAAM,CAAC,MAAM,CACX,GAAG,YAAY,qBAAqB,EACpC,sBAAW,CAAC,2BAA2B,CAAC,QAAQ,EAAE,WAAW,CAAC,EAC9D,sBAAW,CAAC,mBAAmB,CAAC,QAAQ,EAAE,aAAa,EAAE,WAAW,CAAC,EACrE,qCAAU,CACX,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport authService from \"../auth/auth.service\";\nimport { deleteFile, uploadFile } from \"./file-uploader.controller\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport path from \"path\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\n\nconst router: Router = Router();\n\nexport async function getFileUploaderRouter({ fileUpload }: ArkosConfig) {\n const modelModules = await importPrismaModelModules(\"file-upload\");\n let { middlewares = {}, authConfigs = {} } = {};\n\n if (modelModules) {\n ({ middlewares = {}, authConfigs = {} } = modelModules);\n }\n\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n router.use(\n basePathname,\n authService.handleAuthenticationControl(\"View\", authConfigs),\n authService.handleAccessControl(\"View\", \"file-upload\", authConfigs),\n express.static(\n path.resolve(process.cwd(), fileUpload?.baseUploadDir || \"uploads\"),\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStaticOptions || {}\n )\n )\n );\n\n router.post(\n `${basePathname}:fileType`,\n authService.handleAuthenticationControl(\"Create\", authConfigs),\n authService.handleAccessControl(\"Create\", \"file-upload\", authConfigs),\n uploadFile\n );\n\n router.delete(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\"Delete\", authConfigs),\n authService.handleAccessControl(\"Create\", \"file-upload\", authConfigs),\n deleteFile\n );\n\n return router;\n}\n"]}
@@ -1 +1 @@
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"));process.on("uncaughtException",e=>{console.error("UNCAUGHT EXCEPTION! SHUTTING DOWN..."),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.PORT)||8e3,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=_app.listen(o,_arkosConfig.host,()=>{})),_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}
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("UNCAUGHT EXCEPTION! SHUTTING DOWN..."),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}
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AA0EA,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AA/ExB,+BAAkC;AAElC,wFAAyD;AAEzD,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,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,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI;IACtC,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,WAAW;IACrC,UAAU,EAAE;QACV,aAAa,EAAE,SAAS;QACxB,SAAS,EAAE,cAAc;KAC1B;IACD,SAAS,EAAE,KAAK;CACjB,CAAC;AAeF,KAAK,UAAU,OAAO,CAAC,cAA2B,EAAE;IAClD,YAAY,CAAC,SAAS,GAAG,IAAI,CAAC;IAC9B,YAAY,GAAG,IAAA,0BAAS,EAAC,YAAY,EAAE,WAAW,CAAC,CAAC;IAEpD,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC;IAC/B,IAAI,GAAG,MAAM,IAAA,eAAS,EAAC,YAAY,CAAC,CAAC;IAErC,IAAI,IAAI;QACN,iBAAA,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,IAAK,EAAE,GAAG,EAAE;QAUpD,CAAC,CAAC,CAAC;IAEL,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACvD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,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\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\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.PORT) || 8000,\n 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 = _app.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 // console.info(\n // `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m App running on port \\x1b[33m${port}\\x1b[0m, server waiting on http://localhost:${port}`\n // );\n // if (!!process.env.NODE_ENV)\n // console.info(`${`Environment: ${process.env.NODE_ENV}`}`);\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\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
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,E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E;YAC3C,MAAM,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,YAAY,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACrD,OAAO,CAAC,IAAI,CACV,kCAAkC,IAAI,8CAA8C,IAAI,EAAE,CAC3F,CAAC;QAMJ,CAAC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACvD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,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(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\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 // console.info(\n // `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m App running on port \\x1b[33m${port}\\x1b[0m, server waiting on http://localhost:${port}`\n // );\n // if (!!process.env.NODE_ENV)\n // console.info(`${`Environment: ${process.env.NODE_ENV}`}`);\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\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for pass prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\n * ```\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com,\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * @deprecated\n *\n * **Use this instead**:\n *\n * ```ts\n * arkos.init({\n * authentication: {\n * login: {\n * allowedUsernames: [\"email\", \"profile.nickname\"]\n * }\n * }\n * })\n * ```\n *\n * * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n */\n usernameField?: string;\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
1
+ {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for pass prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\n * ```\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com,\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * @deprecated\n *\n * **Use this instead**:\n *\n * ```ts\n * arkos.init({\n * authentication: {\n * login: {\n * allowedUsernames: [\"email\", \"profile.nickname\"]\n * }\n * }\n * })\n * ```\n *\n * * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n */\n usernameField?: string;\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
@@ -12,13 +12,13 @@ const dotenv_helpers_1 = require("../dotenv.helpers");
12
12
  const BUILD_DIR = "build";
13
13
  const MODULE_TYPES = ["cjs", "esm"];
14
14
  function buildCommand(options = {}) {
15
+ const fileExt = (0, fs_helpers_1.getUserFileExtension)();
15
16
  const envFiles = (0, dotenv_helpers_1.loadEnvironmentVariables)();
16
17
  const moduleType = validateModuleType(options.module);
17
18
  try {
18
19
  console.info(`🛠️ Using env variables from ${envFiles?.join(", ")}...`);
19
20
  console.info(`🚀 Building an optimized production ready project with ${moduleType} format...\n`);
20
21
  ensureBuildDir();
21
- const fileExt = (0, fs_helpers_1.getUserFileExtension)();
22
22
  if (fileExt === "ts") {
23
23
  buildTypeScriptProject(options, moduleType);
24
24
  }
@@ -30,6 +30,7 @@ function buildCommand(options = {}) {
30
30
  console.info(`Run the generated build with the start command.\n`);
31
31
  }
32
32
  catch (error) {
33
+ console.info("\n");
33
34
  console.error("❌ Build failed:", error);
34
35
  process.exit(1);
35
36
  }
@@ -194,9 +195,8 @@ function createModulePackageJson(moduleType) {
194
195
  }
195
196
  function cleanupTempConfig(configPath) {
196
197
  try {
197
- if (fs_1.default.existsSync(configPath)) {
198
+ if (fs_1.default.existsSync(configPath))
198
199
  fs_1.default.unlinkSync(configPath);
199
- }
200
200
  }
201
201
  catch (error) {
202
202
  console.warn("Warning: Error cleaning up temporary config:", error);