arkos 1.4.14-canary.5 → 1.4.15-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/app.js +8 -8
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +7 -0
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/errors.js +158 -0
- package/dist/cjs/modules/error-handler/utils/errors.js.map +1 -0
- package/dist/cjs/modules/error-handler/utils/multer-error-handler.js +39 -0
- package/dist/cjs/modules/error-handler/utils/multer-error-handler.js.map +1 -0
- package/dist/cjs/modules/file-upload/file-upload.controller.js +2 -10
- package/dist/cjs/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/cjs/types/arkos-prisma-input.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +22 -24
- package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-controller-template.js +17 -3
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-controller-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-multiple-components.js +3 -5
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js +1 -4
- package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/cjs/utils/initialize-app.js +8 -6
- package/dist/cjs/utils/initialize-app.js.map +1 -1
- package/dist/cjs/utils/setup-app.js +8 -8
- package/dist/cjs/utils/setup-app.js.map +1 -1
- package/dist/esm/app.js +8 -8
- package/dist/esm/app.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +4 -0
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/errors.js +127 -0
- package/dist/esm/modules/error-handler/utils/errors.js.map +1 -0
- package/dist/esm/modules/error-handler/utils/multer-error-handler.js +34 -0
- package/dist/esm/modules/error-handler/utils/multer-error-handler.js.map +1 -0
- package/dist/esm/modules/file-upload/file-upload.controller.js +2 -10
- package/dist/esm/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/esm/types/arkos-prisma-input.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +22 -24
- package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js +14 -3
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-multiple-components.js +3 -5
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
- package/dist/esm/utils/helpers/prisma.helpers.js +1 -4
- package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/esm/utils/initialize-app.js +8 -6
- package/dist/esm/utils/initialize-app.js.map +1 -1
- package/dist/esm/utils/setup-app.js +8 -8
- package/dist/esm/utils/setup-app.js.map +1 -1
- package/dist/types/modules/error-handler/utils/errors.d.ts +176 -0
- package/dist/types/modules/error-handler/utils/multer-error-handler.d.ts +7 -0
- package/dist/types/modules/file-upload/file-upload.controller.d.ts +0 -1
- package/dist/types/types/arkos-prisma-input.d.ts +3 -2
- package/dist/types/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.d.ts +1 -1
- package/package.json +1 -1
package/dist/cjs/app.js
CHANGED
|
@@ -69,6 +69,14 @@ async function bootstrap(initConfig) {
|
|
|
69
69
|
]);
|
|
70
70
|
(0, arkos_config_helpers_1.validateArkosConfig)();
|
|
71
71
|
const middlewaresConfig = arkosConfig?.middlewares;
|
|
72
|
+
if (middlewaresConfig?.requestLogger !== false) {
|
|
73
|
+
if (typeof middlewaresConfig?.requestLogger === "function") {
|
|
74
|
+
exports.app.use(middlewaresConfig.requestLogger);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
exports.app.use(base_middlewares_1.handleRequestLogs);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
72
80
|
if (middlewaresConfig?.compression !== false) {
|
|
73
81
|
if (typeof middlewaresConfig?.compression === "function") {
|
|
74
82
|
exports.app.use(middlewaresConfig.compression);
|
|
@@ -157,14 +165,6 @@ async function bootstrap(initConfig) {
|
|
|
157
165
|
}, middlewaresConfig?.queryParser || {})));
|
|
158
166
|
}
|
|
159
167
|
}
|
|
160
|
-
if (middlewaresConfig?.requestLogger !== false) {
|
|
161
|
-
if (typeof middlewaresConfig?.requestLogger === "function") {
|
|
162
|
-
exports.app.use(middlewaresConfig.requestLogger);
|
|
163
|
-
}
|
|
164
|
-
else {
|
|
165
|
-
exports.app.use(base_middlewares_1.handleRequestLogs);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
168
|
exports.app.use(debugger_service_1.default.logRequestInfo);
|
|
169
169
|
const routersConfig = arkosConfig?.routers;
|
|
170
170
|
if (routersConfig?.welcomeRoute !== false) {
|
package/dist/cjs/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,8BAiMC;AA/ND,mDAAmD;AACnD,gDAAwB;AACxB,kEAAyC;AACzC,4DAA2D;AAC3D,4DAGoC;AACpC,gHAA4E;AAC5E,2DAA+C;AAC/C,8DAAsC;AACtC,sEAAoE;AACpE,mEAAkE;AAClE,iFAA+E;AAC/E,+EAAmE;AACnE,wFAAyD;AACzD,qEAAoE;AACpE,2DAAiE;AACjE,2DAAmD;AACnD,2FAAkE;AAClE,uCAA2C;AAE3C,+EAG8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QAC9C,IAAI,OAAO,iBAAiB,EAAE,YAAY,KAAK,UAAU,EAAE,CAAC;YAC1D,WAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC1C,CAAC;aAAM,CAAC;YACN,WAAG,CAAC,GAAG,CAAC,kCAAY,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;IAED,OAAO,WAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { IRouter, Router } from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\nimport { getArkosConfig } from \"./exports\";\nimport { ArkosInitConfig } from \"./types/arkos-config\";\nimport {\n isAuthenticationEnabled,\n validateArkosConfig,\n} from \"./utils/helpers/arkos-config.helpers\";\nimport { lenientDecode } from \"./utils/helpers/url-helpers\";\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n initConfig: ArkosInitConfig\n): Promise<express.Express> {\n const arkosConfig = getArkosConfig();\n\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n initConfig?.configureApp && (await initConfig?.configureApp(app)),\n ]);\n\n validateArkosConfig();\n const middlewaresConfig = arkosConfig?.middlewares;\n\n if (middlewaresConfig?.compression !== false) {\n if (typeof middlewaresConfig?.compression === \"function\") {\n app.use(middlewaresConfig.compression);\n } else {\n app.use(compression(middlewaresConfig?.compression || {}));\n }\n }\n\n if (middlewaresConfig?.rateLimit !== false) {\n if (typeof middlewaresConfig?.rateLimit === \"function\") {\n app.use(middlewaresConfig.rateLimit);\n } else {\n app.use(\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 300,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n middlewaresConfig?.rateLimit || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.cors !== false) {\n if (typeof middlewaresConfig?.cors === \"function\") {\n app.use(middlewaresConfig.cors);\n } else {\n app.use(\n cors(\n middlewaresConfig?.cors?.customHandler\n ? middlewaresConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = (middlewaresConfig?.cors as any)\n ?.allowedOrigins;\n\n if (allowed === \"*\") cb(null, true);\n else if (Array.isArray(allowed))\n cb(null, !origin || allowed?.includes?.(origin));\n else if (typeof allowed === \"string\")\n cb(null, !origin || allowed === origin);\n else cb(null, false);\n },\n\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n middlewaresConfig?.cors?.options || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.expressJson !== false) {\n if (typeof middlewaresConfig?.expressJson === \"function\") {\n app.use(middlewaresConfig.expressJson);\n } else {\n app.use(express.json(middlewaresConfig?.expressJson || {}));\n }\n }\n\n if (middlewaresConfig?.cookieParser !== false) {\n if (typeof middlewaresConfig?.cookieParser === \"function\") {\n app.use(middlewaresConfig.cookieParser);\n } else {\n const params = Array.isArray(middlewaresConfig?.cookieParser)\n ? middlewaresConfig.cookieParser\n : [];\n app.use(cookieParser(...(params as any))); // FIXME: check types correctly\n }\n }\n\n if (middlewaresConfig?.queryParser !== false) {\n if (typeof middlewaresConfig?.queryParser === \"function\") {\n app.use(middlewaresConfig.queryParser);\n } else {\n app.use(\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n },\n middlewaresConfig?.queryParser || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.requestLogger !== false) {\n if (typeof middlewaresConfig?.requestLogger === \"function\") {\n app.use(middlewaresConfig.requestLogger);\n } else {\n app.use(handleRequestLogs);\n }\n }\n\n app.use(debuggerService.logRequestInfo);\n\n const routersConfig = arkosConfig?.routers;\n\n if (routersConfig?.welcomeRoute !== false) {\n if (typeof routersConfig?.welcomeRoute === \"function\") {\n app.get(\"/api\", routersConfig.welcomeRoute);\n } else {\n app.get(\"/api\", (_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n });\n }\n }\n\n if (initConfig?.use)\n for (const mwOrRouter of initConfig.use) {\n app.use(mwOrRouter as IRouter);\n }\n\n const fileUploadRouter = getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n\n if (isAuthenticationEnabled()) {\n const authRouter = getAuthRouter(arkosConfig) as any;\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n const modelsRouter = getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter as any);\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig, app));\n\n app.use(\"*\", (req) => {\n const url = lenientDecode(req.originalUrl);\n throw new AppError(\n `Route ${req.method.toUpperCase()} ${url} was not found`,\n 404,\n { route: `${req.method.toUpperCase()} ${url}` },\n \"RouteNotFound\"\n );\n });\n\n if (middlewaresConfig?.errorHandler !== false) {\n if (typeof middlewaresConfig?.errorHandler === \"function\") {\n app.use(middlewaresConfig.errorHandler);\n } else {\n app.use(errorHandler);\n }\n }\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,8BAiMC;AA/ND,mDAAmD;AACnD,gDAAwB;AACxB,kEAAyC;AACzC,4DAA2D;AAC3D,4DAGoC;AACpC,gHAA4E;AAC5E,2DAA+C;AAC/C,8DAAsC;AACtC,sEAAoE;AACpE,mEAAkE;AAClE,iFAA+E;AAC/E,+EAAmE;AACnE,wFAAyD;AACzD,qEAAoE;AACpE,2DAAiE;AACjE,2DAAmD;AACnD,2FAAkE;AAClE,uCAA2C;AAE3C,+EAG8C;AAC9C,6DAA4D;AAC/C,QAAA,GAAG,GAAoB,IAAA,iBAAO,GAAE,CAAC;AAC9C,MAAM,iBAAiB,GAAG,IAAA,gBAAM,GAAE,CAAC;AAE5B,KAAK,UAAU,SAAS,CAC7B,UAA2B;IAE3B,MAAM,WAAW,GAAG,IAAA,wBAAc,GAAE,CAAC;IAErC,MAAM,OAAO,CAAC,GAAG,CAAC;QAChB,IAAA,iCAAgB,GAAE;QAClB,IAAA,wCAAuB,EAAC,WAAW,CAAC;QACpC,UAAU,EAAE,YAAY,IAAI,CAAC,MAAM,UAAU,EAAE,YAAY,CAAC,WAAG,CAAC,CAAC;KAClE,CAAC,CAAC;IAEH,IAAA,0CAAmB,GAAE,CAAC;IACtB,MAAM,iBAAiB,GAAG,WAAW,EAAE,WAAW,CAAC;IAEnD,IAAI,iBAAiB,EAAE,aAAa,KAAK,KAAK,EAAE,CAAC;QAC/C,IAAI,OAAO,iBAAiB,EAAE,aAAa,KAAK,UAAU,EAAE,CAAC;YAC3D,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jC,WAAW,CAAC,OAAO,CAAC,gBAAgB,KAAK,IAAI,CAAC;QAEhD,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,IAAA,iCAAgB,EAAC,WAAW,EAAE,WAAG,CAAC,CAAC,CAAC;IAE5D,WAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACnB,MAAM,GAAG,GAAG,IAAA,2BAAa,EAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QAC3C,MAAM,IAAI,wBAAQ,CAChB,SAAS,GAAG,CAAC,MAAM,CAAC,WAAW,EAAE,IAAI,GAAG,gBAAgB,EACxD,GAAG,EACH,EAAE,KAAK,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,WAAW,EAAE,IAAI,GAAG,EAAE,EAAE,EAC/C,eAAe,CAChB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,IAAI,iBAAiB,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;QAC9C,IAAI,OAAO,iBAAiB,EAAE,YAAY,KAAK,UAAU,EAAE,CAAC;YAC1D,WAAG,CAAC,GAAG,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC1C,CAAC;aAAM,CAAC;YACN,WAAG,CAAC,GAAG,CAAC,kCAAY,CAAC,CAAC;QACxB,CAAC;IACH,CAAC;IAED,OAAO,WAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { IRouter, Router } from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\nimport { getArkosConfig } from \"./exports\";\nimport { ArkosInitConfig } from \"./types/arkos-config\";\nimport {\n isAuthenticationEnabled,\n validateArkosConfig,\n} from \"./utils/helpers/arkos-config.helpers\";\nimport { lenientDecode } from \"./utils/helpers/url-helpers\";\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n initConfig: ArkosInitConfig\n): Promise<express.Express> {\n const arkosConfig = getArkosConfig();\n\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n initConfig?.configureApp && (await initConfig?.configureApp(app)),\n ]);\n\n validateArkosConfig();\n const middlewaresConfig = arkosConfig?.middlewares;\n\n if (middlewaresConfig?.requestLogger !== false) {\n if (typeof middlewaresConfig?.requestLogger === \"function\") {\n app.use(middlewaresConfig.requestLogger);\n } else {\n app.use(handleRequestLogs);\n }\n }\n\n if (middlewaresConfig?.compression !== false) {\n if (typeof middlewaresConfig?.compression === \"function\") {\n app.use(middlewaresConfig.compression);\n } else {\n app.use(compression(middlewaresConfig?.compression || {}));\n }\n }\n\n if (middlewaresConfig?.rateLimit !== false) {\n if (typeof middlewaresConfig?.rateLimit === \"function\") {\n app.use(middlewaresConfig.rateLimit);\n } else {\n app.use(\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 300,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n middlewaresConfig?.rateLimit || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.cors !== false) {\n if (typeof middlewaresConfig?.cors === \"function\") {\n app.use(middlewaresConfig.cors);\n } else {\n app.use(\n cors(\n middlewaresConfig?.cors?.customHandler\n ? middlewaresConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = (middlewaresConfig?.cors as any)\n ?.allowedOrigins;\n\n if (allowed === \"*\") cb(null, true);\n else if (Array.isArray(allowed))\n cb(null, !origin || allowed?.includes?.(origin));\n else if (typeof allowed === \"string\")\n cb(null, !origin || allowed === origin);\n else cb(null, false);\n },\n\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n middlewaresConfig?.cors?.options || {}\n )\n )\n );\n }\n }\n\n if (middlewaresConfig?.expressJson !== false) {\n if (typeof middlewaresConfig?.expressJson === \"function\") {\n app.use(middlewaresConfig.expressJson);\n } else {\n app.use(express.json(middlewaresConfig?.expressJson || {}));\n }\n }\n\n if (middlewaresConfig?.cookieParser !== false) {\n if (typeof middlewaresConfig?.cookieParser === \"function\") {\n app.use(middlewaresConfig.cookieParser);\n } else {\n const params = Array.isArray(middlewaresConfig?.cookieParser)\n ? middlewaresConfig.cookieParser\n : [];\n app.use(cookieParser(...(params as any))); // FIXME: check types correctly\n }\n }\n\n if (middlewaresConfig?.queryParser !== false) {\n if (typeof middlewaresConfig?.queryParser === \"function\") {\n app.use(middlewaresConfig.queryParser);\n } else {\n app.use(\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n },\n middlewaresConfig?.queryParser || {}\n )\n )\n );\n }\n }\n\n app.use(debuggerService.logRequestInfo);\n\n const routersConfig = arkosConfig?.routers;\n\n if (routersConfig?.welcomeRoute !== false) {\n if (typeof routersConfig?.welcomeRoute === \"function\") {\n app.get(\"/api\", routersConfig.welcomeRoute);\n } else {\n app.get(\"/api\", (_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n });\n }\n }\n\n if (initConfig?.use)\n for (const mwOrRouter of initConfig.use) {\n app.use(mwOrRouter as IRouter);\n }\n\n const fileUploadRouter = getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n\n if (isAuthenticationEnabled()) {\n const authRouter = getAuthRouter(arkosConfig) as any;\n knowModulesRouter.use(\"/api\", authRouter);\n }\n\n const modelsRouter = getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter as any);\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig, app));\n\n app.use(\"*\", (req) => {\n const url = lenientDecode(req.originalUrl);\n throw new AppError(\n `Route ${req.method.toUpperCase()} ${url} was not found`,\n 404,\n { route: `${req.method.toUpperCase()} ${url}` },\n \"RouteNotFound\"\n );\n });\n\n if (middlewaresConfig?.errorHandler !== false) {\n if (typeof middlewaresConfig?.errorHandler === \"function\") {\n app.use(middlewaresConfig.errorHandler);\n } else {\n app.use(errorHandler);\n }\n }\n\n return app;\n}\n"]}
|
|
@@ -32,10 +32,15 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
32
32
|
return result;
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
35
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
39
|
exports.default = errorHandler;
|
|
37
40
|
const errorControllerHelper = __importStar(require("./utils/error-handler.helpers.js"));
|
|
38
41
|
const server_1 = require("../../server.js");
|
|
42
|
+
const multer_error_handler_1 = __importDefault(require("./utils/multer-error-handler.js"));
|
|
43
|
+
const multer_1 = require("multer");
|
|
39
44
|
function errorHandler(err, req, res, _) {
|
|
40
45
|
console.error("[\x1b[31mError\x1b[0m]:", err);
|
|
41
46
|
err.statusCode = err.statusCode || 500;
|
|
@@ -47,6 +52,8 @@ function errorHandler(err, req, res, _) {
|
|
|
47
52
|
};
|
|
48
53
|
if (process.env.ARKOS_BUILD === "true")
|
|
49
54
|
delete error?.stack;
|
|
55
|
+
if (err.name === "MulterError" || err instanceof multer_1.MulterError)
|
|
56
|
+
error = multer_error_handler_1.default.handle(err);
|
|
50
57
|
if (err.name === "JsonWebTokenError")
|
|
51
58
|
error = errorControllerHelper.handleJWTError();
|
|
52
59
|
if (err.name === "TokenExpiredError")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAsEC;AAxFD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE5D,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC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KAAK,EAAE,KAAK,EAAE,CAAC,IAAI,CAAC;KAChD,CAAC,CAAC;AACL,CAAC;AAcD,SAAS,mBAAmB,CAAC,GAAa,EAAE,CAAU,EAAE,GAAa;IACnE,IAAI,GAAG,CAAC,aAAa;QACnB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE;YACpB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,SAAS;SAC5B,CAAC,CAAC;;QAEH,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;YACnB,MAAM,EAAE,OAAO;YACf,OAAO,EAAE,gDAAgD;YACzD,IAAI,EAAE,qBAAqB;YAC3B,IAAI,EAAE,EAAE;SACT,CAAC,CAAC;AACP,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,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} _ - 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 _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\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 (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n message: error.message,\n ...error,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\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} _ - 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(err: any, _: Request, res: Response): void {\n res.status(err.statusCode).json({\n ...err,\n message: err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\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} _ - 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, _: Request, res: Response): void {\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: \"Internal server error, please try again later.\",\n code: \"InternalServerError\",\n meta: {},\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 (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,+BAyEC;AA7FD,qFAAuE;AACvE,yCAAsC;AACtC,wFAA8D;AAC9D,mCAAqC;AAiBrC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE5D,IAAI,GAAG,CAAC,IAAI,KAAK,aAAa,IAAI,GAAG,YAAY,oBAAW;QAC1D,KAAK,GAAG,8BAAkB,CAAC,MAAM,CAAC,GAA6B,CAAC,CAAC;IAEnE,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;IAEnD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B;QAC5C,KAAK,GAAG,qBAAqB,CAAC,iCAAiC,CAAC,GAAG,CAAC,CAAC;IACvE,IAAI,GAAG,CA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AAC,CAAC,IAAI,CAAC;YAC9B,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE;YACpB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,SAAS;SAC5B,CAAC,CAAC;;QAEH,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;YACnB,MAAM,EAAE,OAAO;YACf,OAAO,EAAE,gDAAgD;YACzD,IAAI,EAAE,qBAAqB;YAC3B,IAAI,EAAE,EAAE;SACT,CAAC,CAAC;AACP,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,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\";\nimport multerErrorHandler from \"./utils/multer-error-handler\";\nimport { MulterError } from \"multer\";\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} _ - 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 _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"MulterError\" || err instanceof MulterError)\n error = multerErrorHandler.handle(err as unknown as MulterError);\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\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 (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n message: error.message,\n ...error,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\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} _ - 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(err: any, _: Request, res: Response): void {\n res.status(err.statusCode).json({\n ...err,\n message: err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\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} _ - 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, _: Request, res: Response): void {\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: \"Internal server error, please try again later.\",\n code: \"InternalServerError\",\n meta: {},\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 (process.env.ARKOS_BUILD !== \"true\") {\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"]}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.GatewayTimeoutError = exports.ServiceUnavailableError = exports.BadGatewayError = exports.NotImplementedError = exports.InternalServerError = exports.TooManyRequestsError = exports.UnprocessableContentError = exports.ImATeapotError = exports.ExpectationFailedError = exports.RangeNotSatisfiableError = exports.UnsupportedMediaTypeError = exports.UriTooLongError = exports.PayloadTooLargeError = exports.PreconditionFailedError = exports.LengthRequiredError = exports.GoneError = exports.ConflictError = exports.RequestTimeoutError = exports.NotAcceptableError = exports.MethodNotAllowedError = exports.NotFoundError = exports.ForbiddenError = exports.PaymentRequiredError = exports.UnauthorizedError = exports.BadRequestError = void 0;
|
|
7
|
+
const app_error_1 = __importDefault(require("./app-error.js"));
|
|
8
|
+
class BadRequestError extends app_error_1.default {
|
|
9
|
+
constructor(message = "Bad Request", code = "BadRequest", meta) {
|
|
10
|
+
super(message, 400, code, meta);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.BadRequestError = BadRequestError;
|
|
14
|
+
class UnauthorizedError extends app_error_1.default {
|
|
15
|
+
constructor(message = "Unauthorized", code = "Unauthorized", meta) {
|
|
16
|
+
super(message, 401, code, meta);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
exports.UnauthorizedError = UnauthorizedError;
|
|
20
|
+
class PaymentRequiredError extends app_error_1.default {
|
|
21
|
+
constructor(message = "Payment Required", code = "PaymentRequired", meta) {
|
|
22
|
+
super(message, 402, code, meta);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
exports.PaymentRequiredError = PaymentRequiredError;
|
|
26
|
+
class ForbiddenError extends app_error_1.default {
|
|
27
|
+
constructor(message = "Forbidden", code = "Forbidden", meta) {
|
|
28
|
+
super(message, 403, code, meta);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
exports.ForbiddenError = ForbiddenError;
|
|
32
|
+
class NotFoundError extends app_error_1.default {
|
|
33
|
+
constructor(message = "Not Found", code = "NotFound", meta) {
|
|
34
|
+
super(message, 404, code, meta);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
exports.NotFoundError = NotFoundError;
|
|
38
|
+
class MethodNotAllowedError extends app_error_1.default {
|
|
39
|
+
constructor(message = "Method Not Allowed", code = "MethodNotAllowed", meta) {
|
|
40
|
+
super(message, 405, code, meta);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
exports.MethodNotAllowedError = MethodNotAllowedError;
|
|
44
|
+
class NotAcceptableError extends app_error_1.default {
|
|
45
|
+
constructor(message = "Not Acceptable", code = "NotAcceptable", meta) {
|
|
46
|
+
super(message, 406, code, meta);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
exports.NotAcceptableError = NotAcceptableError;
|
|
50
|
+
class RequestTimeoutError extends app_error_1.default {
|
|
51
|
+
constructor(message = "Request Timeout", code = "RequestTimeout", meta) {
|
|
52
|
+
super(message, 408, code, meta);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
exports.RequestTimeoutError = RequestTimeoutError;
|
|
56
|
+
class ConflictError extends app_error_1.default {
|
|
57
|
+
constructor(message = "Conflict", code = "Conflict", meta) {
|
|
58
|
+
super(message, 409, code, meta);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
exports.ConflictError = ConflictError;
|
|
62
|
+
class GoneError extends app_error_1.default {
|
|
63
|
+
constructor(message = "Gone", code = "Gone", meta) {
|
|
64
|
+
super(message, 410, code, meta);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
exports.GoneError = GoneError;
|
|
68
|
+
class LengthRequiredError extends app_error_1.default {
|
|
69
|
+
constructor(message = "Length Required", code = "LengthRequired", meta) {
|
|
70
|
+
super(message, 411, code, meta);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
exports.LengthRequiredError = LengthRequiredError;
|
|
74
|
+
class PreconditionFailedError extends app_error_1.default {
|
|
75
|
+
constructor(message = "Precondition Failed", code = "PreconditionFailed", meta) {
|
|
76
|
+
super(message, 412, code, meta);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
exports.PreconditionFailedError = PreconditionFailedError;
|
|
80
|
+
class PayloadTooLargeError extends app_error_1.default {
|
|
81
|
+
constructor(message = "Payload Too Large", code = "PayloadTooLarge", meta) {
|
|
82
|
+
super(message, 413, code, meta);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
exports.PayloadTooLargeError = PayloadTooLargeError;
|
|
86
|
+
class UriTooLongError extends app_error_1.default {
|
|
87
|
+
constructor(message = "URI Too Long", code = "UriTooLong", meta) {
|
|
88
|
+
super(message, 414, code, meta);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
exports.UriTooLongError = UriTooLongError;
|
|
92
|
+
class UnsupportedMediaTypeError extends app_error_1.default {
|
|
93
|
+
constructor(message = "Unsupported Media Type", code = "UnsupportedMediaType", meta) {
|
|
94
|
+
super(message, 415, code, meta);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
exports.UnsupportedMediaTypeError = UnsupportedMediaTypeError;
|
|
98
|
+
class RangeNotSatisfiableError extends app_error_1.default {
|
|
99
|
+
constructor(message = "Range Not Satisfiable", code = "RangeNotSatisfiable", meta) {
|
|
100
|
+
super(message, 416, code, meta);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
exports.RangeNotSatisfiableError = RangeNotSatisfiableError;
|
|
104
|
+
class ExpectationFailedError extends app_error_1.default {
|
|
105
|
+
constructor(message = "Expectation Failed", code = "ExpectationFailed", meta) {
|
|
106
|
+
super(message, 417, code, meta);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
exports.ExpectationFailedError = ExpectationFailedError;
|
|
110
|
+
class ImATeapotError extends app_error_1.default {
|
|
111
|
+
constructor(message = "I'm a teapot", code = "ImATeapot", meta) {
|
|
112
|
+
super(message, 418, code, meta);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
exports.ImATeapotError = ImATeapotError;
|
|
116
|
+
class UnprocessableContentError extends app_error_1.default {
|
|
117
|
+
constructor(message = "Unprocessable Content", code = "UnprocessableContent", meta) {
|
|
118
|
+
super(message, 422, code, meta);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
exports.UnprocessableContentError = UnprocessableContentError;
|
|
122
|
+
class TooManyRequestsError extends app_error_1.default {
|
|
123
|
+
constructor(message = "Too Many Requests", code = "TooManyRequests", meta) {
|
|
124
|
+
super(message, 429, code, meta);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
exports.TooManyRequestsError = TooManyRequestsError;
|
|
128
|
+
class InternalServerError extends app_error_1.default {
|
|
129
|
+
constructor(message = "Internal Server Error", code = "InternalServer", meta) {
|
|
130
|
+
super(message, 500, code, meta);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
exports.InternalServerError = InternalServerError;
|
|
134
|
+
class NotImplementedError extends app_error_1.default {
|
|
135
|
+
constructor(message = "Not Implemented", code = "NotImplemented", meta) {
|
|
136
|
+
super(message, 501, code, meta);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
exports.NotImplementedError = NotImplementedError;
|
|
140
|
+
class BadGatewayError extends app_error_1.default {
|
|
141
|
+
constructor(message = "Bad Gateway", code = "BadGateway", meta) {
|
|
142
|
+
super(message, 502, code, meta);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
exports.BadGatewayError = BadGatewayError;
|
|
146
|
+
class ServiceUnavailableError extends app_error_1.default {
|
|
147
|
+
constructor(message = "Service Unavailable", code = "ServiceUnavailable", meta) {
|
|
148
|
+
super(message, 503, code, meta);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
exports.ServiceUnavailableError = ServiceUnavailableError;
|
|
152
|
+
class GatewayTimeoutError extends app_error_1.default {
|
|
153
|
+
constructor(message = "Gateway Timeout", code = "GatewayTimeout", meta) {
|
|
154
|
+
super(message, 504, code, meta);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
exports.GatewayTimeoutError = GatewayTimeoutError;
|
|
158
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/errors.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAmC;AAMnC,MAAa,eAAgB,SAAQ,mBAAQ;IAC3C,YACE,OAAO,GAAG,aAAa,EACvB,IAAI,GAAG,YAAY,EACnB,IAA0B;QAE1B,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AARD,0CAQC;AAMD,MAAa,iBAAkB,SAAQ,mBAAQ;IAC7C,YACE,OAAO,GAAG,cAAc,EACxB,IAAI,GAAG,cAAc,EACrB,IAA0B;QAE1B,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AARD,8CAQC;AAMD,MAAa,oBAAqB,SAAQ,mBAAQ;IAChD,YACE,OAAO,GAAG,kBAAkB,EAC5B,IAAI,GAAG,iBAAiB,EACxB,IAA0B;QAE1B,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AARD,oDAQC;AAMD,MAAa,cAAe,SAAQ,mBAAQ;IAC1C,YACE,OAAO,GAAG,WAAW,EACrB,IAAI,GAAG,WAAW,EAClB,IAA0B;QAE1B,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AARD,wCAQC;AAMD,MAAa,aAAc,SAAQ,mBAAQ;IACzC,YACE,OAAO,GAAG,WAAW,EACrB,IA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a,eAAgB,SAAQ,mBAAQ;IAC3C,YACE,OAAO,GAAG,aAAa,EACvB,IAAI,GAAG,YAAY,EACnB,IAA0B;QAE1B,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AARD,0CAQC;AAMD,MAAa,uBAAwB,SAAQ,mBAAQ;IACnD,YACE,OAAO,GAAG,qBAAqB,EAC/B,IAAI,GAAG,oBAAoB,EAC3B,IAA0B;QAE1B,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AARD,0DAQC;AAMD,MAAa,mBAAoB,SAAQ,mBAAQ;IAC/C,YACE,OAAO,GAAG,iBAAiB,EAC3B,IAAI,GAAG,gBAAgB,EACvB,IAA0B;QAE1B,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AARD,kDAQC","sourcesContent":["import AppError from \"./app-error\";\n\n/**\n * 400 - Bad Request\n * @example throw new BadRequestError(\"Invalid input\", \"InvalidInput\", { field: \"email\" })\n */\nexport class BadRequestError extends AppError {\n constructor(\n message = \"Bad Request\",\n code = \"BadRequest\",\n meta?: Record<string, any>\n ) {\n super(message, 400, code, meta);\n }\n}\n\n/**\n * 401 - Unauthorized\n * @example throw new UnauthorizedError(\"Invalid token\", \"InvalidToken\")\n */\nexport class UnauthorizedError extends AppError {\n constructor(\n message = \"Unauthorized\",\n code = \"Unauthorized\",\n meta?: Record<string, any>\n ) {\n super(message, 401, code, meta);\n }\n}\n\n/**\n * 402 - Payment Required\n * @example throw new PaymentRequiredError(\"Subscription expired\", \"PaymentRequired\")\n */\nexport class PaymentRequiredError extends AppError {\n constructor(\n message = \"Payment Required\",\n code = \"PaymentRequired\",\n meta?: Record<string, any>\n ) {\n super(message, 402, code, meta);\n }\n}\n\n/**\n * 403 - Forbidden\n * @example throw new ForbiddenError(\"Access denied\", \"Forbidden\", { resource: \"admin\" })\n */\nexport class ForbiddenError extends AppError {\n constructor(\n message = \"Forbidden\",\n code = \"Forbidden\",\n meta?: Record<string, any>\n ) {\n super(message, 403, code, meta);\n }\n}\n\n/**\n * 404 - Not Found\n * @example throw new NotFoundError(\"User not found\", \"NotFound\", { id: 123 })\n */\nexport class NotFoundError extends AppError {\n constructor(\n message = \"Not Found\",\n code = \"NotFound\",\n meta?: Record<string, any>\n ) {\n super(message, 404, code, meta);\n }\n}\n\n/**\n * 405 - Method Not Allowed\n * @example throw new MethodNotAllowedError(\"POST not allowed\", \"MethodNotAllowed\")\n */\nexport class MethodNotAllowedError extends AppError {\n constructor(\n message = \"Method Not Allowed\",\n code = \"MethodNotAllowed\",\n meta?: Record<string, any>\n ) {\n super(message, 405, code, meta);\n }\n}\n\n/**\n * 406 - Not Acceptable\n * @example throw new NotAcceptableError(\"Unsupported format\", \"NotAcceptable\")\n */\nexport class NotAcceptableError extends AppError {\n constructor(\n message = \"Not Acceptable\",\n code = \"NotAcceptable\",\n meta?: Record<string, any>\n ) {\n super(message, 406, code, meta);\n }\n}\n\n/**\n * 408 - Request Timeout\n * @example throw new RequestTimeoutError(\"Upload took too long\", \"RequestTimeout\")\n */\nexport class RequestTimeoutError extends AppError {\n constructor(\n message = \"Request Timeout\",\n code = \"RequestTimeout\",\n meta?: Record<string, any>\n ) {\n super(message, 408, code, meta);\n }\n}\n\n/**\n * 409 - Conflict\n * @example throw new ConflictError(\"Duplicate entry\", \"Conflict\", { field: \"email\" })\n */\nexport class ConflictError extends AppError {\n constructor(\n message = \"Conflict\",\n code = \"Conflict\",\n meta?: Record<string, any>\n ) {\n super(message, 409, code, meta);\n }\n}\n\n/**\n * 410 - Gone\n * @example throw new GoneError(\"Resource deleted\", \"Gone\")\n */\nexport class GoneError extends AppError {\n constructor(message = \"Gone\", code = \"Gone\", meta?: Record<string, any>) {\n super(message, 410, code, meta);\n }\n}\n\n/**\n * 411 - Length Required\n * @example throw new LengthRequiredError(\"Content-Length missing\", \"LengthRequired\")\n */\nexport class LengthRequiredError extends AppError {\n constructor(\n message = \"Length Required\",\n code = \"LengthRequired\",\n meta?: Record<string, any>\n ) {\n super(message, 411, code, meta);\n }\n}\n\n/**\n * 412 - Precondition Failed\n * @example throw new PreconditionFailedError(\"ETag mismatch\", \"PreconditionFailed\")\n */\nexport class PreconditionFailedError extends AppError {\n constructor(\n message = \"Precondition Failed\",\n code = \"PreconditionFailed\",\n meta?: Record<string, any>\n ) {\n super(message, 412, code, meta);\n }\n}\n\n/**\n * 413 - Payload Too Large\n * @example throw new PayloadTooLargeError(\"File exceeds 10MB\", \"PayloadTooLarge\", { max: \"10MB\" })\n */\nexport class PayloadTooLargeError extends AppError {\n constructor(\n message = \"Payload Too Large\",\n code = \"PayloadTooLarge\",\n meta?: Record<string, any>\n ) {\n super(message, 413, code, meta);\n }\n}\n\n/**\n * 414 - URI Too Long\n * @example throw new UriTooLongError(\"Query string too long\", \"UriTooLong\")\n */\nexport class UriTooLongError extends AppError {\n constructor(\n message = \"URI Too Long\",\n code = \"UriTooLong\",\n meta?: Record<string, any>\n ) {\n super(message, 414, code, meta);\n }\n}\n\n/**\n * 415 - Unsupported Media Type\n * @example throw new UnsupportedMediaTypeError(\"Expected JSON\", \"UnsupportedMediaType\")\n */\nexport class UnsupportedMediaTypeError extends AppError {\n constructor(\n message = \"Unsupported Media Type\",\n code = \"UnsupportedMediaType\",\n meta?: Record<string, any>\n ) {\n super(message, 415, code, meta);\n }\n}\n\n/**\n * 416 - Range Not Satisfiable\n * @example throw new RangeNotSatisfiableError(\"Invalid byte range\", \"RangeNotSatisfiable\")\n */\nexport class RangeNotSatisfiableError extends AppError {\n constructor(\n message = \"Range Not Satisfiable\",\n code = \"RangeNotSatisfiable\",\n meta?: Record<string, any>\n ) {\n super(message, 416, code, meta);\n }\n}\n\n/**\n * 417 - Expectation Failed\n * @example throw new ExpectationFailedError(\"Expect header failed\", \"ExpectationFailed\")\n */\nexport class ExpectationFailedError extends AppError {\n constructor(\n message = \"Expectation Failed\",\n code = \"ExpectationFailed\",\n meta?: Record<string, any>\n ) {\n super(message, 417, code, meta);\n }\n}\n\n/**\n * 418 - I'm a teapot\n * @example throw new ImATeapotError(\"Cannot brew coffee\", \"ImATeapot\")\n */\nexport class ImATeapotError extends AppError {\n constructor(\n message = \"I'm a teapot\",\n code = \"ImATeapot\",\n meta?: Record<string, any>\n ) {\n super(message, 418, code, meta);\n }\n}\n\n/**\n * 422 - Unprocessable Content\n * @example throw new UnprocessableContentError(\"Validation failed\", \"ValidationFailed\", { errors: [...] })\n */\nexport class UnprocessableContentError extends AppError {\n constructor(\n message = \"Unprocessable Content\",\n code = \"UnprocessableContent\",\n meta?: Record<string, any>\n ) {\n super(message, 422, code, meta);\n }\n}\n\n/**\n * 429 - Too Many Requests\n * @example throw new TooManyRequestsError(\"Rate limit exceeded\", \"RateLimitExceeded\", { retryAfter: 60 })\n */\nexport class TooManyRequestsError extends AppError {\n constructor(\n message = \"Too Many Requests\",\n code = \"TooManyRequests\",\n meta?: Record<string, any>\n ) {\n super(message, 429, code, meta);\n }\n}\n\n/**\n * 500 - Internal Server Error\n * @example throw new InternalServerError(\"Database connection failed\", \"DatabaseError\")\n */\nexport class InternalServerError extends AppError {\n constructor(\n message = \"Internal Server Error\",\n code = \"InternalServer\",\n meta?: Record<string, any>\n ) {\n super(message, 500, code, meta);\n }\n}\n\n/**\n * 501 - Not Implemented\n * @example throw new NotImplementedError(\"Feature coming soon\", \"NotImplemented\")\n */\nexport class NotImplementedError extends AppError {\n constructor(\n message = \"Not Implemented\",\n code = \"NotImplemented\",\n meta?: Record<string, any>\n ) {\n super(message, 501, code, meta);\n }\n}\n\n/**\n * 502 - Bad Gateway\n * @example throw new BadGatewayError(\"Upstream timeout\", \"BadGateway\")\n */\nexport class BadGatewayError extends AppError {\n constructor(\n message = \"Bad Gateway\",\n code = \"BadGateway\",\n meta?: Record<string, any>\n ) {\n super(message, 502, code, meta);\n }\n}\n\n/**\n * 503 - Service Unavailable\n * @example throw new ServiceUnavailableError(\"Maintenance mode\", \"ServiceUnavailable\", { retryAfter: 300 })\n */\nexport class ServiceUnavailableError extends AppError {\n constructor(\n message = \"Service Unavailable\",\n code = \"ServiceUnavailable\",\n meta?: Record<string, any>\n ) {\n super(message, 503, code, meta);\n }\n}\n\n/**\n * 504 - Gateway Timeout\n * @example throw new GatewayTimeoutError(\"Upstream timeout\", \"GatewayTimeout\")\n */\nexport class GatewayTimeoutError extends AppError {\n constructor(\n message = \"Gateway Timeout\",\n code = \"GatewayTimeout\",\n meta?: Record<string, any>\n ) {\n super(message, 504, code, meta);\n }\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
const app_error_1 = __importDefault(require("./app-error.js"));
|
|
7
|
+
class MulterErrorHandler {
|
|
8
|
+
handle(err) {
|
|
9
|
+
switch (err.code) {
|
|
10
|
+
case "LIMIT_UNEXPECTED_FILE":
|
|
11
|
+
return new app_error_1.default(`Unexpected file field '${err.field}'`, 400, "UnexpectedFileField", {
|
|
12
|
+
hint: "Ensure the field name matches the expected upload configuration",
|
|
13
|
+
});
|
|
14
|
+
case "LIMIT_FILE_SIZE":
|
|
15
|
+
return new app_error_1.default(`File in field '${err.field}' exceeds the maximum allowed size`, 413, "FileTooLarge", {
|
|
16
|
+
hint: "Upload a smaller file or contact the server administrator to increase the limit",
|
|
17
|
+
});
|
|
18
|
+
case "LIMIT_FILE_COUNT":
|
|
19
|
+
return new app_error_1.default(`Too many files uploaded`, 400, "TooManyFiles", {
|
|
20
|
+
hint: "Reduce the number of files and try again",
|
|
21
|
+
});
|
|
22
|
+
case "LIMIT_FIELD_COUNT":
|
|
23
|
+
return new app_error_1.default(`Too many fields in the request`, 400, "TooManyFields", { hint: "Reduce the number of form fields and try again" });
|
|
24
|
+
case "LIMIT_PART_COUNT":
|
|
25
|
+
return new app_error_1.default(`Too many parts in the multipart request`, 400, "TooManyParts", { hint: "Reduce the number of parts in your multipart request" });
|
|
26
|
+
case "LIMIT_FIELD_KEY":
|
|
27
|
+
return new app_error_1.default(`A field name in the request is too long`, 400, "FieldNameTooLong", { hint: "Shorten your form field names" });
|
|
28
|
+
case "LIMIT_FIELD_VALUE":
|
|
29
|
+
return new app_error_1.default(`Value of field '${err.field}' is too long`, 400, "FieldValueTooLong", { hint: "Shorten the value and try again" });
|
|
30
|
+
case "MISSING_FIELD_NAME":
|
|
31
|
+
return new app_error_1.default(`A file was uploaded without a field name`, 400, "MissingFieldName", { hint: "Ensure all file inputs have a valid field name" });
|
|
32
|
+
default:
|
|
33
|
+
return new app_error_1.default(`An unexpected file upload error occurred`, 500, "FileUploadError");
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const multerErrorHandler = new MulterErrorHandler();
|
|
38
|
+
exports.default = multerErrorHandler;
|
|
39
|
+
//# sourceMappingURL=multer-error-handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"multer-error-handler.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/multer-error-handler.ts"],"names":[],"mappings":";;;;;AACA,4DAAmC;AAEnC,MAAM,kBAAkB;IACtB,MAAM,CAAC,GAAuB;QAC5B,QAAQ,GAAG,CAAC,IAAI,EAAE,CAAC;YACjB,KAAK,uBAAuB;gBAC1B,OAAO,IAAI,mBAAQ,CACjB,0BAA0B,GAAG,CAAC,KAAK,GAAG,EACtC,GAAG,EACH,qBAAqB,EACrB;oBACE,IAAI,EAAE,iEAAiE;iBACxE,CACF,CAAC;YACJ,KAAK,iBAAiB;gBACpB,OAAO,IAAI,mBAAQ,CACjB,kBAAkB,GAAG,CAAC,KAAK,oCAAoC,EAC/D,GAAG,EACH,cAAc,EACd;oBACE,IAAI,EAAE,iFAAiF;iBACxF,CACF,CAAC;YACJ,KAAK,kBAAkB;gBACrB,OAAO,IAAI,mBAAQ,CAAC,yBAAyB,EAAE,GAAG,EAAE,cAAc,EAAE;oBAClE,IAAI,EAAE,0CAA0C;iBACjD,CAAC,CAAC;YACL,KAAK,mBAAmB;gBACtB,OAAO,IAAI,mBAAQ,CACjB,gCAAgC,EAChC,GAAG,EACH,eAAe,EACf,EAAE,IAAI,EAAE,gDAAgD,EAAE,CAC3D,CAAC;YACJ,KAAK,kBAAkB;gBACrB,OAAO,IAAI,mBAAQ,CACjB,yCAAyC,EACzC,GAAG,EACH,cAAc,EACd,EAAE,IAAI,EAAE,sDAAsD,EAAE,CACjE,CAAC;YACJ,KAAK,iBAAiB;gBACpB,OAAO,IAAI,mBAAQ,CACjB,yCAAyC,EACzC,GAAG,EACH,kBAAkB,EAClB,EAAE,IAAI,EAAE,+BAA+B,EAAE,CAC1C,CAAC;YACJ,KAAK,mBAAmB;gBACtB,OAAO,IAAI,mBAAQ,CACjB,mBAAmB,GAAG,CAAC,KAAK,eAAe,EAC3C,GAAG,EACH,mBAAmB,EACnB,EAAE,IAAI,EAAE,iCAAiC,EAAE,CAC5C,CAAC;YACJ,KAAK,oBAAoB;gBACvB,OAAO,IAAI,mBAAQ,CACjB,0CAA0C,EAC1C,GAAG,EACH,kBAAkB,EAClB,EAAE,IAAI,EAAE,gDAAgD,EAAE,CAC3D,CAAC;YACJ;gBACE,OAAO,IAAI,mBAAQ,CACjB,0CAA0C,EAC1C,GAAG,EACH,iBAAiB,CAClB,CAAC;QACN,CAAC;IACH,CAAC;CACF;AAED,MAAM,kBAAkB,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAEpD,kBAAe,kBAAkB,CAAC","sourcesContent":["import multer from \"multer\";\nimport AppError from \"./app-error\";\n\nclass MulterErrorHandler {\n handle(err: multer.MulterError): AppError {\n switch (err.code) {\n case \"LIMIT_UNEXPECTED_FILE\":\n return new AppError(\n `Unexpected file field '${err.field}'`,\n 400,\n \"UnexpectedFileField\",\n {\n hint: \"Ensure the field name matches the expected upload configuration\",\n }\n );\n case \"LIMIT_FILE_SIZE\":\n return new AppError(\n `File in field '${err.field}' exceeds the maximum allowed size`,\n 413,\n \"FileTooLarge\",\n {\n hint: \"Upload a smaller file or contact the server administrator to increase the limit\",\n }\n );\n case \"LIMIT_FILE_COUNT\":\n return new AppError(`Too many files uploaded`, 400, \"TooManyFiles\", {\n hint: \"Reduce the number of files and try again\",\n });\n case \"LIMIT_FIELD_COUNT\":\n return new AppError(\n `Too many fields in the request`,\n 400,\n \"TooManyFields\",\n { hint: \"Reduce the number of form fields and try again\" }\n );\n case \"LIMIT_PART_COUNT\":\n return new AppError(\n `Too many parts in the multipart request`,\n 400,\n \"TooManyParts\",\n { hint: \"Reduce the number of parts in your multipart request\" }\n );\n case \"LIMIT_FIELD_KEY\":\n return new AppError(\n `A field name in the request is too long`,\n 400,\n \"FieldNameTooLong\",\n { hint: \"Shorten your form field names\" }\n );\n case \"LIMIT_FIELD_VALUE\":\n return new AppError(\n `Value of field '${err.field}' is too long`,\n 400,\n \"FieldValueTooLong\",\n { hint: \"Shorten the value and try again\" }\n );\n case \"MISSING_FIELD_NAME\":\n return new AppError(\n `A file was uploaded without a field name`,\n 400,\n \"MissingFieldName\",\n { hint: \"Ensure all file inputs have a valid field name\" }\n );\n default:\n return new AppError(\n `An unexpected file upload error occurred`,\n 500,\n \"FileUploadError\"\n );\n }\n }\n}\n\nconst multerErrorHandler = new MulterErrorHandler();\n\nexport default multerErrorHandler;\n"]}
|
|
@@ -12,8 +12,6 @@ const catch_async_1 = __importDefault(require("../error-handler/utils/catch-asyn
|
|
|
12
12
|
const server_1 = require("../../server.js");
|
|
13
13
|
const file_upload_helpers_1 = require("./utils/helpers/file-upload.helpers.js");
|
|
14
14
|
const dynamic_loader_1 = require("../../utils/dynamic-loader.js");
|
|
15
|
-
const multer_1 = require("multer");
|
|
16
|
-
const utils_1 = require("../../exports/utils/index.js");
|
|
17
15
|
class FileUploadController {
|
|
18
16
|
constructor() {
|
|
19
17
|
this.uploadFile = (0, catch_async_1.default)(async (req, res, next) => {
|
|
@@ -51,7 +49,7 @@ class FileUploadController {
|
|
|
51
49
|
}
|
|
52
50
|
uploader.handleMultipleUpload()(req, res, async (err) => {
|
|
53
51
|
if (err)
|
|
54
|
-
|
|
52
|
+
throw err;
|
|
55
53
|
let data;
|
|
56
54
|
if (req.files && Array.isArray(req.files) && req.files.length > 0) {
|
|
57
55
|
if (fileType === "images") {
|
|
@@ -173,7 +171,7 @@ class FileUploadController {
|
|
|
173
171
|
}
|
|
174
172
|
uploader.handleMultipleUpload()(req, res, async (err) => {
|
|
175
173
|
if (err)
|
|
176
|
-
|
|
174
|
+
throw err;
|
|
177
175
|
if (!req.file &&
|
|
178
176
|
(!req.files || !Array.isArray(req.files) || req.files.length === 0))
|
|
179
177
|
return next(new app_error_1.default("No new file uploaded", 400, "MissingNewFile"));
|
|
@@ -236,12 +234,6 @@ class FileUploadController {
|
|
|
236
234
|
});
|
|
237
235
|
});
|
|
238
236
|
}
|
|
239
|
-
handleUploadError(err, next) {
|
|
240
|
-
if (err instanceof multer_1.MulterError)
|
|
241
|
-
return next(new app_error_1.default(err.message, 400, (0, utils_1.pascalCase)(err.code || "FileUploadError")));
|
|
242
|
-
else
|
|
243
|
-
return next(err);
|
|
244
|
-
}
|
|
245
237
|
}
|
|
246
238
|
exports.FileUploadController = FileUploadController;
|
|
247
239
|
const fileUploadController = new FileUploadController();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,+DAAiE;AACjE,mCAAqC;AACrC,+CAAiD;AAKjD,MA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,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE;4BAClC,CAAC,CAAC,2BAA2B;4BAC7B,CAAC,CAAC,4BAA4B;iBACnC,CAAC;gBAEF,IAAI,IAAI,CAAC,YAAY,CAAC,eAAe,EAAE,CAAC;oBACrC,GAAW,CAAC,YAAY,GAAG,WAAW,CAAC;oBACxC,GAAG,CAAC,YAAY,GAAG,WAAW,CAAC;oBAC/B,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,WAAW,CAAC;oBAC7B,GAAW,CAAC,cAAc,GAAG,GAAG,CAAC;oBAClC,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;oBACzB,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC;oBACxB,OAAO,IAAI,EAAE,CAAC;gBAChB,CAAC;gBAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IAqDJ,CAAC;IA3YS,iBAAiB,CAAC,GAAQ,EAAE,IAAuB;QACzD,IAAI,GAAG,YAAY,oBAAW;YAC5B,OAAO,IAAI,CACT,IAAI,mBAAQ,CACV,GAAG,CAAC,OAAO,EACX,GAAG,EACH,IAAA,kBAAU,EAAC,GAAG,CAAC,IAAI,IAAI,iBAAiB,CAAC,CAC1C,CACF,CAAC;;YACC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;CAiYF;AA5YD,oDA4YC;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,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 { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { MulterError } from \"multer\";\nimport { pascalCase } from \"../../exports/utils\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n private handleUploadError(err: any, next: ArkosNextFunction) {\n if (err instanceof MulterError)\n return next(\n new AppError(\n err.message,\n 400,\n pascalCase(err.code || \"FileUploadError\")\n )\n );\n else return next(err);\n }\n\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: 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.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\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 const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\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(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\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.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 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.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\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(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\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 await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\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.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\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 const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\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(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) return this.handleUploadError(err, next);\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, 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.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 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, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(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
|
+
{"version":3,"file":"file-upload.controller.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.controller.ts"],"names":[],"mappings":";;;;;;AAAA,iFAAwD;AACxD,+DAG+B;AAC/B,gDAAwB;AACxB,4CAAoB;AACpB,qFAA4D;AAC5D,yCAA8C;AAC9C,6EAAgF;AAEhF,+DAAiE;AAKjE,MAAa,oBAAoB;IAAjC;QAeE,eAAU,GAAG,IAAA,qBAA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AC,YAAY,CAAC,eAAe,EAAE,CAAC;oBACrC,GAAW,CAAC,YAAY,GAAG,WAAW,CAAC;oBACxC,GAAG,CAAC,YAAY,GAAG,WAAW,CAAC;oBAC/B,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,WAAW,CAAC;oBAC7B,GAAW,CAAC,cAAc,GAAG,GAAG,CAAC;oBAClC,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;oBACzB,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC;oBACxB,OAAO,IAAI,EAAE,CAAC;gBAChB,CAAC;gBAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IAqDJ,CAAC;CAAA;AAhYD,oDAgYC;AAcD,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,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 { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\n\n/**\n * Handles files uploads and allow to be extended\n */\nexport class FileUploadController {\n /**\n * Model-specific interceptors loaded from model modules\n * @private\n */\n private interceptors: 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.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\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 const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\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(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return next(\n new AppError(\n `No file or files were attached on field ${fileType} on the request body as form data.`,\n 400,\n \"NoFileOrFilesAttached\"\n )\n );\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.interceptors?.afterUploadFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 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.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\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(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n try {\n const { fileUpload } = getArkosConfig();\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\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 await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n if (this.interceptors.afterDeleteFile) {\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n } catch (error) {\n if (error instanceof AppError) return next(error);\n\n return next(new AppError(\"File not found\", 404, \"FileNotFound\"));\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.interceptors =\n getModuleComponents(\"file-upload\")?.interceptors || {};\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 const uploadPath = path.resolve(\n path.join(process.cwd(), baseUploadDir, fileType)\n );\n try {\n await fs.promises.access(uploadPath);\n } catch (err) {\n await fs.promises.mkdir(uploadPath, { recursive: true });\n }\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(\n new AppError(\"Invalid file type\", 400, \"InvalidFileType\")\n );\n }\n\n uploader.handleMultipleUpload()(req, res, async (err) => {\n if (err) throw err;\n\n if (\n !req.file &&\n (!req.files || !Array.isArray(req.files) || req.files.length === 0)\n )\n return next(\n new AppError(\"No new file uploaded\", 400, \"MissingNewFile\")\n );\n\n if (fileName && fileName.trim() !== \"\") {\n try {\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${\n req.originalUrl\n }`;\n await uploader.deleteFileByUrl(oldFileUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n } catch (error) {\n console.warn(`Could not delete old file: ${fileName}`, error);\n }\n }\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n if (fileType === \"images\") {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n if (fileType === \"images\") {\n data = await processImage(req, next, 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.interceptors.afterUpdateFile) {\n (res as any).originalData = jsonContent;\n req.responseData = jsonContent;\n res.locals.data = jsonContent;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 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, _: ArkosNextFunction) => {\n // const { fileName, fileType } = req.params;\n\n // const filePath = path.join(\".\", \"uploads\", fileType, fileName);\n // try {\n // await fs.promises.access(filePath);\n // } catch (err) {\n // throw new AppError(\"File not found\", 404);\n // }\n\n // const fileStat = await fs.promises.stat(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"]}
|