arkos 1.2.13-beta → 1.2.13-test.1

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 (222) hide show
  1. package/dist/cjs/app.js +138 -1
  2. package/dist/cjs/app.js.map +1 -1
  3. package/dist/cjs/index.js +22 -0
  4. package/dist/cjs/modules/base/base.middlewares.js +4 -4
  5. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  6. package/dist/cjs/modules/swagger/swagger.router.js +62 -43
  7. package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
  8. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +82 -62
  9. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
  10. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js +23 -16
  11. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js.map +1 -1
  12. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js +1 -1
  13. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js.map +1 -1
  14. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js +40 -11
  15. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js.map +1 -1
  16. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js +419 -9
  17. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js.map +1 -1
  18. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +253 -0
  19. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -0
  20. package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js +31 -20
  21. package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
  22. package/dist/cjs/paths.js +9 -1
  23. package/dist/cjs/server.js +85 -5
  24. package/dist/cjs/server.js.map +1 -1
  25. package/dist/cjs/types/arkos-config.js.map +1 -1
  26. package/dist/cjs/utils/cli/dev.js +7 -7
  27. package/dist/cjs/utils/cli/dev.js.map +1 -1
  28. package/dist/cjs/utils/cli/start.js +4 -3
  29. package/dist/cjs/utils/cli/start.js.map +1 -1
  30. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js +1 -1
  31. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-service-template.js +1 -1
  32. package/dist/cjs/utils/features/api.features.js +1 -1
  33. package/dist/cjs/utils/features/api.features.js.map +1 -1
  34. package/dist/cjs/utils/helpers/global.helpers.js.map +1 -1
  35. package/dist/cjs/utils/helpers/models.helpers.js +43 -21
  36. package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
  37. package/dist/cjs/utils/prisma/enhaced-prisma-json-schema-generator.js +451 -0
  38. package/dist/cjs/utils/prisma/enhaced-prisma-json-schema-generator.js.map +1 -0
  39. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +88 -0
  40. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -0
  41. package/dist/cjs/utils/prisma/prisma-schema-parser.js +158 -0
  42. package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -0
  43. package/dist/cjs/utils/prisma/types.js +3 -0
  44. package/dist/cjs/utils/prisma/types.js.map +1 -0
  45. package/dist/esm/index.d.mts +280 -0
  46. package/dist/esm/index.mjs +22 -0
  47. package/dist/exports/index.js +1 -0
  48. package/dist/types/arkos-config.js +1 -0
  49. package/dist/types/auth.js +1 -0
  50. package/dist/types/index.js +1 -0
  51. package/dist/types/modules/base/base.middlewares.d.ts +4 -4
  52. package/dist/types/modules/swagger/utils/helpers/get-authentication-json-schema-paths.d.ts +2 -1
  53. package/dist/types/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.d.ts +2 -1
  54. package/dist/types/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.d.ts +2 -1
  55. package/dist/types/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.d.ts +2 -1
  56. package/dist/types/modules/swagger/utils/helpers/missing-json-schemas-generator.d.ts +34 -0
  57. package/dist/types/modules/swagger/utils/helpers/swagger.router.helpers.d.ts +2 -2
  58. package/dist/types/router-config.js +1 -0
  59. package/dist/types/types/arkos-config.d.ts +3 -1
  60. package/dist/types/utils/helpers/models.helpers.d.ts +18 -4
  61. package/dist/types/utils/prisma/enhaced-prisma-json-schema-generator.d.ts +34 -0
  62. package/dist/types/utils/prisma/prisma-json-schema-generator.d.ts +10 -0
  63. package/dist/types/utils/prisma/prisma-schema-parser.d.ts +18 -0
  64. package/dist/types/utils/prisma/types.d.ts +48 -0
  65. package/dist/utils/arkos-env.js +1 -0
  66. package/dist/utils/dotenv.helpers.js +1 -0
  67. package/dist/utils/sheu.js +1 -0
  68. package/dist/utils/validate-dto.js +1 -0
  69. package/dist/utils/validate-schema.js +1 -0
  70. package/package.json +11 -6
  71. package/dist/esm/app.js +0 -1
  72. package/dist/esm/app.js.map +0 -1
  73. package/dist/esm/exports/auth/index.js +0 -2
  74. package/dist/esm/exports/auth/index.js.map +0 -1
  75. package/dist/esm/exports/controllers/index.js +0 -4
  76. package/dist/esm/exports/controllers/index.js.map +0 -1
  77. package/dist/esm/exports/error-handler/index.js +0 -4
  78. package/dist/esm/exports/error-handler/index.js.map +0 -1
  79. package/dist/esm/exports/index.js +0 -8
  80. package/dist/esm/exports/index.js.map +0 -1
  81. package/dist/esm/exports/middlewares/index.js +0 -2
  82. package/dist/esm/exports/middlewares/index.js.map +0 -1
  83. package/dist/esm/exports/prisma/index.js +0 -3
  84. package/dist/esm/exports/prisma/index.js.map +0 -1
  85. package/dist/esm/exports/services/index.js +0 -9
  86. package/dist/esm/exports/services/index.js.map +0 -1
  87. package/dist/esm/exports/utils/index.js +0 -4
  88. package/dist/esm/exports/utils/index.js.map +0 -1
  89. package/dist/esm/exports/validation/index.js +0 -4
  90. package/dist/esm/exports/validation/index.js.map +0 -1
  91. package/dist/esm/modules/auth/auth.controller.js +0 -187
  92. package/dist/esm/modules/auth/auth.controller.js.map +0 -1
  93. package/dist/esm/modules/auth/auth.router.js +0 -44
  94. package/dist/esm/modules/auth/auth.router.js.map +0 -1
  95. package/dist/esm/modules/auth/auth.service.js +0 -178
  96. package/dist/esm/modules/auth/auth.service.js.map +0 -1
  97. package/dist/esm/modules/auth/utils/helpers/auth.controller.helpers.js +0 -73
  98. package/dist/esm/modules/auth/utils/helpers/auth.controller.helpers.js.map +0 -1
  99. package/dist/esm/modules/base/base.controller.js +0 -150
  100. package/dist/esm/modules/base/base.controller.js.map +0 -1
  101. package/dist/esm/modules/base/base.middlewares.js +0 -81
  102. package/dist/esm/modules/base/base.middlewares.js.map +0 -1
  103. package/dist/esm/modules/base/base.router.js +0 -17
  104. package/dist/esm/modules/base/base.router.js.map +0 -1
  105. package/dist/esm/modules/base/base.service.js +0 -120
  106. package/dist/esm/modules/base/base.service.js.map +0 -1
  107. package/dist/esm/modules/base/utils/helpers/base.controller.helpers.js +0 -77
  108. package/dist/esm/modules/base/utils/helpers/base.controller.helpers.js.map +0 -1
  109. package/dist/esm/modules/base/utils/helpers/base.middlewares.helpers.js +0 -44
  110. package/dist/esm/modules/base/utils/helpers/base.middlewares.helpers.js.map +0 -1
  111. package/dist/esm/modules/base/utils/helpers/base.router.helpers.js +0 -89
  112. package/dist/esm/modules/base/utils/helpers/base.router.helpers.js.map +0 -1
  113. package/dist/esm/modules/base/utils/helpers/base.service.helpers.js +0 -165
  114. package/dist/esm/modules/base/utils/helpers/base.service.helpers.js.map +0 -1
  115. package/dist/esm/modules/email/email.service.js +0 -97
  116. package/dist/esm/modules/email/email.service.js.map +0 -1
  117. package/dist/esm/modules/error-handler/error-handler.controller.js +0 -107
  118. package/dist/esm/modules/error-handler/error-handler.controller.js.map +0 -1
  119. package/dist/esm/modules/error-handler/utils/app-error.js +0 -15
  120. package/dist/esm/modules/error-handler/utils/app-error.js.map +0 -1
  121. package/dist/esm/modules/error-handler/utils/catch-async.js +0 -10
  122. package/dist/esm/modules/error-handler/utils/catch-async.js.map +0 -1
  123. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +0 -160
  124. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +0 -1
  125. package/dist/esm/modules/file-upload/file-upload.controller.js +0 -266
  126. package/dist/esm/modules/file-upload/file-upload.controller.js.map +0 -1
  127. package/dist/esm/modules/file-upload/file-upload.router.js +0 -38
  128. package/dist/esm/modules/file-upload/file-upload.router.js.map +0 -1
  129. package/dist/esm/modules/file-upload/file-upload.service.js +0 -314
  130. package/dist/esm/modules/file-upload/file-upload.service.js.map +0 -1
  131. package/dist/esm/modules/file-upload/utils/helpers/file-upload.helpers.js +0 -87
  132. package/dist/esm/modules/file-upload/utils/helpers/file-upload.helpers.js.map +0 -1
  133. package/dist/esm/modules/swagger/swagger.router.js +0 -94
  134. package/dist/esm/modules/swagger/swagger.router.js.map +0 -1
  135. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +0 -247
  136. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +0 -1
  137. package/dist/esm/modules/swagger/utils/helpers/get-system-json-schema-paths.js +0 -63
  138. package/dist/esm/modules/swagger/utils/helpers/get-system-json-schema-paths.js.map +0 -1
  139. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js +0 -38
  140. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js.map +0 -1
  141. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js +0 -19
  142. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js.map +0 -1
  143. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js +0 -24
  144. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js.map +0 -1
  145. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js +0 -436
  146. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js.map +0 -1
  147. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js +0 -159
  148. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js.map +0 -1
  149. package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js +0 -84
  150. package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js.map +0 -1
  151. package/dist/esm/paths.js +0 -1
  152. package/dist/esm/paths.js.map +0 -1
  153. package/dist/esm/server.js +0 -5
  154. package/dist/esm/server.js.map +0 -1
  155. package/dist/esm/types/arkos-config.js +0 -2
  156. package/dist/esm/types/arkos-config.js.map +0 -1
  157. package/dist/esm/types/auth.js +0 -2
  158. package/dist/esm/types/auth.js.map +0 -1
  159. package/dist/esm/types/index.js +0 -8
  160. package/dist/esm/types/index.js.map +0 -1
  161. package/dist/esm/types/router-config.js +0 -2
  162. package/dist/esm/types/router-config.js.map +0 -1
  163. package/dist/esm/utils/arkos-env.js +0 -7
  164. package/dist/esm/utils/arkos-env.js.map +0 -1
  165. package/dist/esm/utils/cli/build.js +0 -206
  166. package/dist/esm/utils/cli/build.js.map +0 -1
  167. package/dist/esm/utils/cli/dev.js +0 -249
  168. package/dist/esm/utils/cli/dev.js.map +0 -1
  169. package/dist/esm/utils/cli/generate.js +0 -183
  170. package/dist/esm/utils/cli/generate.js.map +0 -1
  171. package/dist/esm/utils/cli/index.js +0 -74
  172. package/dist/esm/utils/cli/index.js.map +0 -1
  173. package/dist/esm/utils/cli/start.js +0 -86
  174. package/dist/esm/utils/cli/start.js.map +0 -1
  175. package/dist/esm/utils/cli/utils/cli.helpers.js +0 -16
  176. package/dist/esm/utils/cli/utils/cli.helpers.js.map +0 -1
  177. package/dist/esm/utils/cli/utils/template-generator/templates/generate-auth-configs-template.js +0 -33
  178. package/dist/esm/utils/cli/utils/template-generator/templates/generate-auth-configs-template.js.map +0 -1
  179. package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js +0 -18
  180. package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js.map +0 -1
  181. package/dist/esm/utils/cli/utils/template-generator/templates/generate-middlewares.js +0 -232
  182. package/dist/esm/utils/cli/utils/template-generator/templates/generate-middlewares.js.map +0 -1
  183. package/dist/esm/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js +0 -61
  184. package/dist/esm/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js.map +0 -1
  185. package/dist/esm/utils/cli/utils/template-generator/templates/generate-router-template.js +0 -37
  186. package/dist/esm/utils/cli/utils/template-generator/templates/generate-router-template.js.map +0 -1
  187. package/dist/esm/utils/cli/utils/template-generator/templates/generate-service-template.js +0 -32
  188. package/dist/esm/utils/cli/utils/template-generator/templates/generate-service-template.js.map +0 -1
  189. package/dist/esm/utils/cli/utils/template-generators.js +0 -25
  190. package/dist/esm/utils/cli/utils/template-generators.js.map +0 -1
  191. package/dist/esm/utils/dotenv.helpers.js +0 -37
  192. package/dist/esm/utils/dotenv.helpers.js.map +0 -1
  193. package/dist/esm/utils/features/api.features.js +0 -160
  194. package/dist/esm/utils/features/api.features.js.map +0 -1
  195. package/dist/esm/utils/features/change-case.features.js +0 -31
  196. package/dist/esm/utils/features/change-case.features.js.map +0 -1
  197. package/dist/esm/utils/helpers/api.features.helpers.js +0 -103
  198. package/dist/esm/utils/helpers/api.features.helpers.js.map +0 -1
  199. package/dist/esm/utils/helpers/change-case.helpers.js +0 -161
  200. package/dist/esm/utils/helpers/change-case.helpers.js.map +0 -1
  201. package/dist/esm/utils/helpers/deepmerge.helper.js +0 -113
  202. package/dist/esm/utils/helpers/deepmerge.helper.js.map +0 -1
  203. package/dist/esm/utils/helpers/fs.helpers.js +0 -52
  204. package/dist/esm/utils/helpers/fs.helpers.js.map +0 -1
  205. package/dist/esm/utils/helpers/global.helpers.js +0 -47
  206. package/dist/esm/utils/helpers/global.helpers.js.map +0 -1
  207. package/dist/esm/utils/helpers/models.helpers.js +0 -300
  208. package/dist/esm/utils/helpers/models.helpers.js.map +0 -1
  209. package/dist/esm/utils/helpers/prisma.helpers.js +0 -44
  210. package/dist/esm/utils/helpers/prisma.helpers.js.map +0 -1
  211. package/dist/esm/utils/helpers/query-parser.helpers.js +0 -40
  212. package/dist/esm/utils/helpers/query-parser.helpers.js.map +0 -1
  213. package/dist/esm/utils/helpers/routers.helpers.js +0 -16
  214. package/dist/esm/utils/helpers/routers.helpers.js.map +0 -1
  215. package/dist/esm/utils/helpers/text.helpers.js +0 -22
  216. package/dist/esm/utils/helpers/text.helpers.js.map +0 -1
  217. package/dist/esm/utils/sheu.js +0 -117
  218. package/dist/esm/utils/sheu.js.map +0 -1
  219. package/dist/esm/utils/validate-dto.js +0 -11
  220. package/dist/esm/utils/validate-dto.js.map +0 -1
  221. package/dist/esm/utils/validate-schema.js +0 -9
  222. package/dist/esm/utils/validate-schema.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AACzC,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiBtC,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,IAAkB;IAElB,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG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,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;SACrB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,yBAAyB;KACnC,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n next: NextFunction\n): void {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n if (!error.isOperational) error = new AppError(\"Something went wrong!\", 500);\n\n // Send the error response for production environment\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
@@ -1,15 +0,0 @@
1
- class AppError extends Error {
2
- constructor(message, statusCode, meta, code) {
3
- super(message);
4
- this.message = message;
5
- this.statusCode = statusCode;
6
- this.status = `${statusCode}`.startsWith("4") ? "fail" : "error";
7
- this.isOperational = true;
8
- this.code = code;
9
- this.meta = meta;
10
- this.missing = false;
11
- Error.captureStackTrace(this, this.constructor);
12
- }
13
- }
14
- export default AppError;
15
- //# sourceMappingURL=app-error.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"app-error.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/app-error.ts"],"names":[],"mappings":"AAgCA,MAAM,QAAS,SAAQ,KAAK;IAgB1B,YACE,OAAe,EACf,UAAkB,EAClB,IAA0B,EAC1B,IAAa;QAEb,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,GAAG,UAAU,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;QACjE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QAErB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAClD,CAAC;CACF;AAED,eAAe,QAAQ,CAAC","sourcesContent":["/**\n * Custom error class for handling application errors.\n *\n * @extends {Error}\n *\n * @property {number} statusCode - HTTP status code of the error.\n * @property {string} status - Status message derived from the status code (`fail` for 4xx, `error` for 5xx).\n * @property {boolean} [missing=false] - Flag to indicate if a resource is missing.\n * @property {boolean} isOperational - Indicates if the error is operational (intended for client visibility).\n * @property {string} [code] - Optional error code for categorization.\n * @property {Record<string, any>} [meta] - Additional metadata related to the error.\n *\n * @example\n * ```typescript\n *\n * function getUser(id: string) {\n * if (!id) {\n * throw new AppError('User ID is required', 400, { field: 'id' }, 'USER_ID_MISSING');\n * }\n * // Simulate a user not found scenario\n * throw new AppError('User not found', 404, { userId: id }, 'USER_NOT_FOUND');\n * }\n *\n * try {\n * getUser('');\n * } catch (error) {\n * if (error instanceof AppError) {\n * console.error(`Error: ${error.message}, Code: ${error.code}, Status: ${error.status}`);\n * }\n * }\n * ```\n */\nclass AppError extends Error {\n statusCode: number;\n status: string;\n public missing?: boolean;\n public isOperational: boolean;\n code?: string;\n meta?: Record<string, any>;\n\n /**\n * Creates an instance of AppError.\n *\n * @param {string} message - The error message.\n * @param {number} statusCode - The HTTP status code.\n * @param {Record<string, any>} [meta] - Additional metadata for debugging or client feedback.\n * @param {string} [code] - A custom error code for categorization.\n */\n constructor(\n message: string,\n statusCode: number,\n meta?: Record<string, any>,\n code?: string\n ) {\n super(message);\n\n this.message = message;\n this.statusCode = statusCode;\n this.status = `${statusCode}`.startsWith(\"4\") ? \"fail\" : \"error\";\n this.isOperational = true;\n this.code = code;\n this.meta = meta;\n this.missing = false;\n\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\nexport default AppError;\n"]}
@@ -1,10 +0,0 @@
1
- const catchAsync = (fn) => async (req, res, next) => {
2
- try {
3
- return (await fn(req, res, next));
4
- }
5
- catch (err) {
6
- next(err);
7
- }
8
- };
9
- export default catchAsync;
10
- //# sourceMappingURL=catch-async.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"catch-async.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/catch-async.ts"],"names":[],"mappings":"AAwBA,MAAM,UAAU,GACd,CAAC,EAAuB,EAAE,EAAE,CAC5B,KAAK,EACH,GAAiB,EACjB,GAAkB,EAClB,IAAuB,EACR,EAAE;IACjB,IAAI,CAAC;QACH,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAS,CAAC;IAC5C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,GAAG,CAAC,CAAC;IACZ,CAAC;AACH,CAAC,CAAC;AAIJ,eAAe,UAAU,CAAC","sourcesContent":["import {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../../types\";\n\n/**\n * Used to wrap request handlers and middleware for automatic catch async errors and throw to next to invoke the global error handler\n *\n * @param {ArkosRequestHandler} fn - an express request handler or middleware that will be called with req, res, next, with catch attached for error handling\n * @returns\n *\n * @example\n * ```typescript\n * import { ArkosRequest, ArkosResponse, ArkosNextFunction } from 'arkos'\n *\n * export const getManyPosts = catchAsync(async\n * (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n * const posts = await getSomePosts()\n * res.status(200).json({ data: posts })\n * })\n * ```\n */\nconst catchAsync =\n (fn: ArkosRequestHandler) =>\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ): Promise<void> => {\n try {\n return (await fn(req, res, next)) as void;\n } catch (err) {\n next(err);\n }\n };\n\nexport type CatchAsyncReturnType = ReturnType<typeof catchAsync>;\n\nexport default catchAsync;\n"]}
@@ -1,160 +0,0 @@
1
- import AppError from "./app-error.js";
2
- export function handleJWTError() {
3
- return new AppError("Invalid token. Please log in again!", 401);
4
- }
5
- export function handleJWTExpired() {
6
- return new AppError("Your token has expired, Please log again!", 401);
7
- }
8
- export function handlePrismaClientValidationError(err) {
9
- const message = err?.message.split("\n")[err?.message.split("\n").length - 1];
10
- return new AppError(message, 400);
11
- }
12
- export function handleAuthenticationError(err) {
13
- const message = "Authentication failed against the database server. Please check your credentials.";
14
- return new AppError(message, 401);
15
- }
16
- export function handleServerNotReachableError(err) {
17
- const message = "The database server is not reachable. Verify your connection string or ensure the server is online.";
18
- return new AppError(message, 503);
19
- }
20
- export function handleConnectionTimeoutError(err) {
21
- const message = "Connection to the database timed out. Please check server performance or network connectivity.";
22
- return new AppError(message, 504);
23
- }
24
- export function handleDatabaseNotFoundError(err) {
25
- const message = "The specified database does not exist on the server.";
26
- return new AppError(message, 404);
27
- }
28
- export function handleEnvironmentVariableError(err) {
29
- const missingVars = err?.missing || "unknown environment variables";
30
- const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;
31
- return new AppError(message, 500);
32
- }
33
- export function handleFieldValueTooLargeError(err) {
34
- const message = `The value for the field "${err?.meta?.field_name}" is too large. Please provide a smaller value.`;
35
- return new AppError(message, 400);
36
- }
37
- export function handleRecordNotFoundError(err) {
38
- const message = "No record found for the given query. Ensure the query parameters are correct.";
39
- return new AppError(message, 404);
40
- }
41
- export function handleUniqueConstraintError(err) {
42
- const field = err?.meta?.target || "unknown field";
43
- const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;
44
- return new AppError(message, 409);
45
- }
46
- export function handleForeignKeyConstraintError(err) {
47
- const message = "Foreign key constraint violation. Ensure that the referenced record exists.";
48
- return new AppError(message, 400);
49
- }
50
- export function handleConstraintFailedError(err) {
51
- const constraint = err?.meta?.constraint || "unknown constraint";
52
- const message = `A database constraint "${constraint}" failed. Please review your input data.`;
53
- return new AppError(message, 400);
54
- }
55
- export function handleInvalidFieldValueError(err) {
56
- const fieldName = err?.meta?.field_name || "unknown field";
57
- const message = `Invalid value provided for the field "${fieldName}". Please provide a valid value.`;
58
- return new AppError(message, 400);
59
- }
60
- export function handleInvalidFieldProvidedError(err) {
61
- const fieldName = err?.meta?.field_name || "unknown field";
62
- const message = `The field "${fieldName}" has been provided with an invalid value. Check the data and try again.`;
63
- return new AppError(message, 400);
64
- }
65
- export function handleDataValidationError(err) {
66
- const message = "Data validation error occurred. Please ensure all fields meet the required criteria.";
67
- return new AppError(message, 400);
68
- }
69
- export function handleQueryParsingError(err) {
70
- const query = err?.meta?.query || "unknown query";
71
- const message = `Failed to parse the query: "${query}". Check the syntax and structure.`;
72
- return new AppError(message, 400);
73
- }
74
- export function handleInvalidQueryFormatError(err) {
75
- const query = err?.meta?.query || "unknown query";
76
- const message = `The query format is invalid: "${query}". Ensure the query adheres to the expected format.`;
77
- return new AppError(message, 400);
78
- }
79
- export function handleRawQueryExecutionError(err) {
80
- const message = "An error occurred during the execution of a raw query. Verify the query and try again.";
81
- return new AppError(message, 500);
82
- }
83
- export function handleNullConstraintViolationError(err) {
84
- const fieldName = err?.meta?.field_name || "unknown field";
85
- const message = `The field "${fieldName}" cannot be null. Please provide a value.`;
86
- return new AppError(message, 400);
87
- }
88
- export function handleSchemaCreationFailedError(err) {
89
- const message = "Failed to create the database schema. Verify the schema definition and try again.";
90
- return new AppError(message, 500);
91
- }
92
- export function handleMigrationAlreadyAppliedError(err) {
93
- const migrationName = err?.meta?.migration || "unknown migration";
94
- const message = `The migration "${migrationName}" has already been applied to the database.`;
95
- return new AppError(message, 409);
96
- }
97
- export function handleMigrationScriptFailedError(err) {
98
- const migrationName = err?.meta?.migration || "unknown migration";
99
- const message = `The migration script "${migrationName}" failed. Review the script and resolve any issues.`;
100
- return new AppError(message, 500);
101
- }
102
- export function handleVersionMismatchError(err) {
103
- const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;
104
- return new AppError(message, 400);
105
- }
106
- export function handleMigrationFileReadError(err) {
107
- const migrationFile = err?.meta?.migration_file || "unknown file";
108
- const message = `Failed to read the migration file "${migrationFile}". Ensure the file exists and is accessible.`;
109
- return new AppError(message, 500);
110
- }
111
- export function handleSchemaDriftError(err) {
112
- const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;
113
- return new AppError(message, 400);
114
- }
115
- export function handleSchemaSyntaxError(err) {
116
- const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;
117
- return new AppError(message, 500);
118
- }
119
- export function handleClientTypeError(err) {
120
- const message = `Type error, Ensure proper usage of methods and correct data types.`;
121
- return new AppError(message, 400);
122
- }
123
- export function handleDynamicQueryError(err) {
124
- const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;
125
- return new AppError(message, 400);
126
- }
127
- export function handleRelationLoadingError(err) {
128
- const relation = err?.meta?.relation || "unknown relation";
129
- const message = `Error loading relation "${relation}". Ensure it is correctly defined and included in the query.`;
130
- return new AppError(message, 400);
131
- }
132
- export function handleBinaryError(err) {
133
- const binaryName = err?.meta?.binary || "unknown binary";
134
- const message = `Error with Prisma binary "${binaryName}". Ensure the binary is properly installed and compatible.`;
135
- return new AppError(message, 500);
136
- }
137
- export function handleNetworkError(err) {
138
- const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;
139
- return new AppError(message, 500);
140
- }
141
- export function handleUnhandledPromiseError(err) {
142
- const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;
143
- return new AppError(message, 500);
144
- }
145
- export function handleDataTypeError(err) {
146
- const field = err?.meta?.field || "unknown field";
147
- const expectedType = err?.meta?.expected_type || "unknown type";
148
- const message = `Invalid data type for field "${field}". Expected type: ${expectedType}.`;
149
- return new AppError(message, 400);
150
- }
151
- export function handleEmptyResultError(err) {
152
- const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;
153
- return new AppError(message, 404);
154
- }
155
- export function handleNonExistingRecord(err) {
156
- const message = err?.meta?.cause ||
157
- `Operation could not be completed as the required record was not found`;
158
- return new AppError(message, 404, err.meta || {}, "PrismaRecordNotFound");
159
- }
160
- //# sourceMappingURL=error-handler.helpers.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,aAAa,CAAC;AASnC,MAAM,UAAU,cAAc;IAC5B,OAAO,IAAI,QAAQ,CAAC,qCAAqC,EAAE,GAAG,CAAC,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AC;IAClD,MAAM,YAAY,GAAG,GAAG,EAAE,IAAI,EAAE,aAAa,IAAI,cAAc,CAAC;IAChE,MAAM,OAAO,GAAG,gCAAgC,KAAK,qBAAqB,YAAY,GAAG,CAAC;IAC1F,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,GAAa;IAClD,MAAM,OAAO,GAAG,6FAA6F,CAAC;IAC9G,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,GAGvC;IACC,MAAM,OAAO,GACX,GAAG,EAAE,IAAI,EAAE,KAAK;QAChB,uEAAuE,CAAC;IAC1E,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,sBAAsB,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string; // Prisma-specific error code\n message: string; // Error message\n meta?: Record<string, any>; // Metadata provided by Prisma\n name?: string; // Error name\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message = err?.message.split(\"\\n\")[err?.message.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(err: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(err: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(err: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(err: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(err: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(message, 409);\n}\n\nexport function handleForeignKeyConstraintError(err: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(err: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(err: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(err: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(err: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(err: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(err: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(err: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(err: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(err: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(err: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(err: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as the required record was not found`;\n return new AppError(message, 404, err.meta || {}, \"PrismaRecordNotFound\");\n}\n"]}
@@ -1,266 +0,0 @@
1
- import AppError from "../error-handler/utils/app-error.js";
2
- import { getFileUploadServices, } from "./file-upload.service.js";
3
- import path from "path";
4
- import fs from "fs";
5
- import catchAsync from "../error-handler/utils/catch-async.js";
6
- import { getArkosConfig } from "../../server.js";
7
- import { processFile, processImage } from "./utils/helpers/file-upload.helpers.js";
8
- import { accessAsync, mkdirAsync, statAsync, } from "../../utils/helpers/fs.helpers.js";
9
- import { getModelModules } from "../../utils/helpers/models.helpers.js";
10
- class FileUploadController {
11
- constructor() {
12
- this.uploadFile = catchAsync(async (req, res, next) => {
13
- this.middlewares = getModelModules("file-upload")?.middlewares || {};
14
- const { fileType } = req.params;
15
- const { format, width, height, resizeTo } = req.query;
16
- const options = { format, width, height, resizeTo };
17
- const { documentUploadService, fileUploadService, imageUploadService, videoUploadService, } = getFileUploadServices();
18
- const { fileUpload } = getArkosConfig();
19
- const baseUploadDir = fileUpload?.baseUploadDir || "/uploads";
20
- const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);
21
- try {
22
- await accessAsync(uploadPath);
23
- }
24
- catch (err) {
25
- await mkdirAsync(uploadPath, { recursive: true });
26
- }
27
- let uploader;
28
- switch (fileType) {
29
- case "images":
30
- uploader = imageUploadService;
31
- break;
32
- case "videos":
33
- uploader = videoUploadService;
34
- break;
35
- case "documents":
36
- uploader = documentUploadService;
37
- break;
38
- case "files":
39
- uploader = fileUploadService;
40
- break;
41
- default:
42
- return next(new AppError("Invalid file type", 400));
43
- }
44
- uploader.handleMultipleUpload()(req, res, async (err) => {
45
- if (err)
46
- return next(err);
47
- let data;
48
- if (req.files && Array.isArray(req.files) && req.files.length > 0) {
49
- if (fileType === "images") {
50
- data = await Promise.all(req.files.map((file) => processImage(req, file.path, options)));
51
- }
52
- else {
53
- data = await Promise.all(req.files.map((file) => processFile(req, file.path)));
54
- }
55
- data = data.filter((url) => url !== null);
56
- }
57
- else if (req.file) {
58
- if (fileType === "images") {
59
- data = await processImage(req, req.file.path, options);
60
- }
61
- else {
62
- data = await processFile(req, req.file.path);
63
- }
64
- }
65
- else {
66
- return next(new AppError("No file uploaded", 400));
67
- }
68
- const jsonContent = {
69
- success: true,
70
- data,
71
- message: Array.isArray(data)
72
- ? `${data.length} files uploaded successfully`
73
- : "File uploaded successfully",
74
- };
75
- if (this.middlewares?.afterUploadFile) {
76
- req.responseData = jsonContent;
77
- req.responseStatus = 200;
78
- return next();
79
- }
80
- res.status(200).json(jsonContent);
81
- });
82
- });
83
- this.deleteFile = catchAsync(async (req, res, next) => {
84
- this.middlewares = getModelModules("file-upload")?.middlewares || {};
85
- const { fileType, fileName } = req.params;
86
- const { documentUploadService, fileUploadService, imageUploadService, videoUploadService, } = getFileUploadServices();
87
- let uploader;
88
- switch (fileType) {
89
- case "images":
90
- uploader = imageUploadService;
91
- break;
92
- case "videos":
93
- uploader = videoUploadService;
94
- break;
95
- case "documents":
96
- uploader = documentUploadService;
97
- break;
98
- case "files":
99
- uploader = fileUploadService;
100
- break;
101
- default:
102
- return next(new AppError("Invalid file type", 400));
103
- }
104
- try {
105
- const { fileUpload } = getArkosConfig();
106
- const baseUploadRoute = fileUpload?.baseRoute || "/api/uploads";
107
- const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
108
- const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
109
- if (isExpectedUrlPattern) {
110
- const fullUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
111
- await uploader.deleteFileByUrl(fullUrl);
112
- }
113
- else {
114
- await uploader.deleteFileByName(fileName, fileType);
115
- }
116
- if (this.middlewares.afterDeleteFile) {
117
- req.responseStatus = 204;
118
- return next();
119
- }
120
- res.status(204).json();
121
- }
122
- catch (error) {
123
- if (error instanceof AppError) {
124
- return next(error);
125
- }
126
- return next(new AppError("File not found", 404));
127
- }
128
- });
129
- this.updateFile = catchAsync(async (req, res, next) => {
130
- this.middlewares = getModelModules("file-upload")?.middlewares || {};
131
- const { fileType, fileName } = req.params;
132
- const { format, width, height, resizeTo } = req.query;
133
- const options = { format, width, height, resizeTo };
134
- const { documentUploadService, fileUploadService, imageUploadService, videoUploadService, } = getFileUploadServices();
135
- const { fileUpload } = getArkosConfig();
136
- const baseUploadDir = fileUpload?.baseUploadDir || "/uploads";
137
- const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);
138
- try {
139
- await accessAsync(uploadPath);
140
- }
141
- catch (err) {
142
- await mkdirAsync(uploadPath, { recursive: true });
143
- }
144
- let uploader;
145
- switch (fileType) {
146
- case "images":
147
- uploader = imageUploadService;
148
- break;
149
- case "videos":
150
- uploader = videoUploadService;
151
- break;
152
- case "documents":
153
- uploader = documentUploadService;
154
- break;
155
- case "files":
156
- uploader = fileUploadService;
157
- break;
158
- default:
159
- return next(new AppError("Invalid file type", 400));
160
- }
161
- uploader.handleMultipleUpload()(req, res, async (err) => {
162
- if (err)
163
- return next(err);
164
- if (!req.file &&
165
- (!req.files || !Array.isArray(req.files) || req.files.length === 0)) {
166
- return next(new AppError("No new file uploaded", 400));
167
- }
168
- if (fileName && fileName.trim() !== "") {
169
- try {
170
- const baseUploadRoute = fileUpload?.baseRoute || "/api/uploads";
171
- const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
172
- const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
173
- if (isExpectedUrlPattern) {
174
- const oldFileUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
175
- await uploader.deleteFileByUrl(oldFileUrl);
176
- }
177
- else {
178
- await uploader.deleteFileByName(fileName, fileType);
179
- }
180
- }
181
- catch (error) {
182
- console.warn(`Could not delete old file: ${fileName}`, error);
183
- }
184
- }
185
- let data;
186
- if (req.files && Array.isArray(req.files) && req.files.length > 0) {
187
- if (fileType === "images") {
188
- data = await Promise.all(req.files.map((file) => processImage(req, file.path, options)));
189
- }
190
- else {
191
- data = await Promise.all(req.files.map((file) => processFile(req, file.path)));
192
- }
193
- data = data.filter((url) => url !== null);
194
- }
195
- else if (req.file) {
196
- if (fileType === "images") {
197
- data = await processImage(req, req.file.path, options);
198
- }
199
- else {
200
- data = await processFile(req, req.file.path);
201
- }
202
- }
203
- const jsonContent = {
204
- success: true,
205
- data,
206
- message: Array.isArray(data)
207
- ? fileName && fileName.trim() !== ""
208
- ? `File updated successfully. ${data.length} new files uploaded`
209
- : `${data.length} files uploaded successfully`
210
- : fileName && fileName.trim() !== ""
211
- ? "File updated successfully"
212
- : "File uploaded successfully",
213
- };
214
- if (this.middlewares.afterUpdateFile) {
215
- req.responseData = jsonContent;
216
- req.responseStatus = 200;
217
- return next();
218
- }
219
- res.status(200).json(jsonContent);
220
- });
221
- });
222
- this.streamFile = catchAsync(async (req, res, next) => {
223
- const { fileName, fileType } = req.params;
224
- const filePath = path.join(".", "uploads", fileType, fileName);
225
- try {
226
- await accessAsync(filePath);
227
- }
228
- catch (err) {
229
- throw new AppError("File not found", 404);
230
- }
231
- const fileStat = await statAsync(filePath);
232
- const fileSize = fileStat.size;
233
- const range = req.headers.range;
234
- if (range) {
235
- const [partialStart, partialEnd] = range
236
- .replace(/bytes=/, "")
237
- .split("-");
238
- const start = parseInt(partialStart, 10) || 0;
239
- const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;
240
- if (start >= fileSize || end >= fileSize) {
241
- res.status(416).json({ error: "Range Not Satisfiable" });
242
- return;
243
- }
244
- res.writeHead(206, {
245
- "Content-Range": `bytes ${start}-${end}/${fileSize}`,
246
- "Accept-Ranges": "bytes",
247
- "Content-Length": end - start + 1,
248
- "Content-Type": "application/octet-stream",
249
- "Content-Disposition": `inline; filename="${fileName}"`,
250
- });
251
- fs.createReadStream(filePath, { start, end }).pipe(res);
252
- }
253
- else {
254
- res.writeHead(200, {
255
- "Content-Length": fileSize,
256
- "Content-Type": "application/octet-stream",
257
- "Content-Disposition": `inline; filename="${fileName}"`,
258
- });
259
- fs.createReadStream(filePath).pipe(res);
260
- }
261
- });
262
- }
263
- }
264
- const fileUploadController = new FileUploadController();
265
- export default fileUploadController;
266
- //# sourceMappingURL=file-upload.controller.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAEL,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,c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AE;oBACjB,eAAe,EAAE,SAAS,KAAK,IAAI,GAAG,IAAI,QAAQ,EAAE;oBACpD,eAAe,EAAE,OAAO;oBACxB,gBAAgB,EAAE,GAAG,GAAG,KAAK,GAAG,CAAC;oBACjC,cAAc,EAAE,0BAA0B;oBAC1C,qBAAqB,EAAE,qBAAqB,QAAQ,GAAG;iBACxD,CAAC,CAAC;gBAEH,EAAE,CAAC,gBAAgB,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1D,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE;oBACjB,gBAAgB,EAAE,QAAQ;oBAC1B,cAAc,EAAE,0BAA0B;oBAC1C,qBAAqB,EAAE,qBAAqB,QAAQ,GAAG;iBACxD,CAAC,CAAC;gBACH,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1C,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;CAAA;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,eAAe,oBAAoB,CAAC","sourcesContent":["import AppError from \"../error-handler/utils/app-error\";\nimport {\n FileUploadService,\n getFileUploadServices,\n} from \"./file-upload.service\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { getArkosConfig } from \"../../server\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport {\n accessAsync,\n mkdirAsync,\n statAsync,\n} from \"../../utils/helpers/fs.helpers\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModelModules } from \"../../utils/helpers/models.helpers\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nclass FileUploadController {\n /**\n * Model-specific middlewares loaded from model modules\n * @private\n */\n private middlewares: any;\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n uploadFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.middlewares = getModelModules(\"file-upload\")?.middlewares || {};\n\n const { fileType } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Ensure upload directory exists\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await accessAsync(uploadPath);\n } catch (err) {\n // Create directory if it doesn't exist\n await mkdirAsync(uploadPath, { recursive: true });\n }\n\n // Select the appropriate uploader service based on file type\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n // Handle the file upload\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n // Process all uploaded files\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n // Process multiple image files with image transformations\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n // Just store other file types without processing\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n if (fileType === \"images\") {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(new AppError(\"No file uploaded\", 400));\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? `${data.length} files uploaded successfully`\n : \"File uploaded successfully\",\n };\n\n if (this.middlewares?.afterUploadFile) {\n req.responseData = jsonContent;\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Handles file deletion requests\n *\n * Supports paths outside of the project directory with '../' prefix\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n deleteFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.middlewares = getModelModules(\"file-upload\")?.middlewares || {};\n\n const { fileType, fileName } = req.params;\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // This checks if the URL follows the expected format: /api/files/{fileType}/{fileName}\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // Build the expected URL for this request\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n\n // URL matches expected pattern, use deleteFileByUrl\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.middlewares.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n // Handle different types of errors\n if (error instanceof AppError) {\n return next(error);\n }\n // File doesn't exist or other error\n return next(new AppError(\"File not found\", 404));\n }\n }\n );\n\n /**\n * Handles file update requests by deleting the old file and uploading a new one\n * @param {ArkosRequest} req - Arkos request object\n * @param {ArkosResponse} res - Arkos response object\n * @param {ArkosNextFunction} next - Arkos next middleware function\n */\n updateFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n this.middlewares = getModelModules(\"file-upload\")?.middlewares || {};\n\n const { fileType, fileName } = req.params;\n const { format, width, height, resizeTo } = req.query;\n const options = { format, width, height, resizeTo };\n\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Ensure upload directory exists\n const uploadPath = path.resolve(process.cwd(), baseUploadDir, fileType);\n try {\n await accessAsync(uploadPath);\n } catch (err) {\n // Create directory if it doesn't exist\n await mkdirAsync(uploadPath, { recursive: true });\n }\n\n // Select the appropriate uploader service based on file type\n let uploader: FileUploadService;\n switch (fileType) {\n case \"images\":\n uploader = imageUploadService;\n break;\n case \"videos\":\n uploader = videoUploadService;\n break;\n case \"documents\":\n uploader = documentUploadService;\n break;\n case \"files\":\n uploader = fileUploadService;\n break;\n default:\n return next(new AppError(\"Invalid file type\", 400));\n }\n\n // Handle the file upload\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return next(err);\n\n // Check if new file was uploaded\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n ) {\n return next(new AppError(\"No new file uploaded\", 400));\n }\n\n // Only attempt to delete old file if fileName is specified\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Check if the URL follows the expected format\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n // URL matches expected pattern, use deleteFileByUrl\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n // URL doesn't match expected pattern, use deleteFileByName\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n // Log the error but continue with upload - old file might not exist\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n // Process the new uploaded file(s)\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n // Process multiple image files with image transformations\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n // Just store other file types without processing\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n if (fileType === \"images\") {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n }\n\n const jsonContent = {\n success: true,\n data,\n message: Array.isArray(data)\n ? fileName && fileName.trim() !== \"\"\n ? `File updated successfully. ${data.length} new files uploaded`\n : `${data.length} files uploaded successfully`\n : fileName && fileName.trim() !== \"\"\n ? \"File updated successfully\"\n : \"File uploaded successfully\",\n };\n\n if (this.middlewares.afterUpdateFile) {\n req.responseData = jsonContent;\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json(jsonContent);\n });\n }\n );\n\n /**\n * Not implemented yet\n *\n * @deprecated\n */\n streamFile = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const { fileName, fileType } = req.params;\n\n const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n try {\n await accessAsync(filePath);\n } catch (err) {\n throw new AppError(\"File not found\", 404);\n }\n\n const fileStat = await statAsync(filePath);\n const fileSize = fileStat.size;\n const range = req.headers.range;\n\n if (range) {\n const [partialStart, partialEnd] = range\n .replace(/bytes=/, \"\")\n .split(\"-\");\n const start = parseInt(partialStart, 10) || 0;\n const end = partialEnd ? parseInt(partialEnd, 10) : fileSize - 1;\n\n if (start >= fileSize || end >= fileSize) {\n res.status(416).json({ error: \"Range Not Satisfiable\" });\n return;\n }\n\n res.writeHead(206, {\n \"Content-Range\": `bytes ${start}-${end}/${fileSize}`,\n \"Accept-Ranges\": \"bytes\",\n \"Content-Length\": end - start + 1,\n \"Content-Type\": \"application/octet-stream\",\n \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n });\n\n fs.createReadStream(filePath, { start, end }).pipe(res);\n } else {\n res.writeHead(200, {\n \"Content-Length\": fileSize,\n \"Content-Type\": \"application/octet-stream\",\n \"Content-Disposition\": `inline; filename=\"${fileName}\"`,\n });\n fs.createReadStream(filePath).pipe(res);\n }\n }\n );\n}\n\n/**\n * Controller instance responsible for handling file upload operations.\n * Manages the processing and routing of file upload requests.\n *\n * @remarks\n * This controller handles various file upload operations including validation,\n * storage, and response management.\n *\n * @instance\n * @constant\n * @see {@link https://www.arkosjs.com/docs/api-reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
@@ -1,38 +0,0 @@
1
- import { Router } from "express";
2
- import { importPrismaModelModules } from "../../utils/helpers/models.helpers.js";
3
- import authService from "../auth/auth.service.js";
4
- import fileUploadController from "./file-upload.controller.js";
5
- import path from "path";
6
- import express from "express";
7
- import deepmerge from "../../utils/helpers/deepmerge.helper.js";
8
- import { sendResponse } from "../base/base.middlewares.js";
9
- import { processMiddleware } from "../../utils/helpers/routers.helpers.js";
10
- import { adjustRequestUrl } from "./utils/helpers/file-upload.helpers.js";
11
- const router = Router();
12
- export async function getFileUploadRouter(arkosConfig) {
13
- const { fileUpload } = arkosConfig;
14
- const modelModules = await importPrismaModelModules("file-upload", arkosConfig);
15
- let { middlewares = {}, authConfigs = {} } = {};
16
- if (modelModules) {
17
- ({ middlewares = {}, authConfigs = {} } = modelModules);
18
- }
19
- let basePathname = fileUpload?.baseRoute || "/api/uploads/";
20
- if (!basePathname.startsWith("/"))
21
- basePathname = "/" + basePathname;
22
- if (!basePathname.endsWith("/"))
23
- basePathname = basePathname + "/";
24
- router.get(`${basePathname}*`, authService.handleAuthenticationControl("View", authConfigs.authenticationControl), authService.handleAccessControl("View", "file-upload", authConfigs.accessControl), ...processMiddleware(middlewares?.beforeFindFile), adjustRequestUrl, express.static(path.resolve(process.cwd(), fileUpload?.baseUploadDir || "uploads"), deepmerge({
25
- maxAge: "1y",
26
- etag: true,
27
- lastModified: true,
28
- dotfiles: "ignore",
29
- fallthrough: true,
30
- index: false,
31
- cacheControl: true,
32
- }, fileUpload?.expressStaticOptions || {})));
33
- router.post(`${basePathname}:fileType`, authService.handleAuthenticationControl("Create", authConfigs.authenticationControl), authService.handleAccessControl("Create", "file-upload", authConfigs.accessControl), ...processMiddleware(middlewares?.beforeUploadFile), fileUploadController.uploadFile, ...processMiddleware(middlewares?.afterUploadFile), sendResponse);
34
- router.patch(`${basePathname}:fileType/:fileName`, authService.handleAuthenticationControl("Update", authConfigs.authenticationControl), authService.handleAccessControl("Update", "file-upload", authConfigs.accessControl), ...processMiddleware(middlewares?.beforeUpdateFile), fileUploadController.updateFile, ...processMiddleware(middlewares?.afterUpdateFile), sendResponse);
35
- router.delete(`${basePathname}:fileType/:fileName`, authService.handleAuthenticationControl("Delete", authConfigs.authenticationControl), authService.handleAccessControl("Delete", "file-upload", authConfigs.accessControl), ...processMiddleware(middlewares?.beforeDeleteFile), fileUploadController.deleteFile, ...processMiddleware(middlewares?.afterDeleteFile), sendResponse);
36
- return router;
37
- }
38
- //# sourceMappingURL=file-upload.router.js.map