arkos 2.0.0-next.13 → 2.0.0-next.16
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/README.md +144 -145
- package/cli.js +1 -0
- package/dist/cjs/app.js +7 -0
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/exports/error-handler/index.js +15 -0
- package/dist/cjs/exports/error-handler/index.js.map +1 -1
- package/dist/cjs/modules/auth/auth.router.js +3 -0
- package/dist/cjs/modules/auth/auth.router.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +2 -0
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/base/base.controller.js +15 -3
- package/dist/cjs/modules/base/base.controller.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +19 -12
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/base.service.js +5 -1
- package/dist/cjs/modules/base/base.service.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js +9 -0
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +25 -42
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/app-error.js +0 -1
- package/dist/cjs/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +8 -9
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.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 +10 -14
- package/dist/cjs/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/cjs/modules/file-upload/file-upload.router.js +2 -0
- package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +8 -2
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js +18 -0
- package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/get-swagger-default-configs.js +5 -5
- package/dist/cjs/modules/swagger/utils/helpers/get-swagger-default-configs.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
- package/dist/cjs/types/arkos-prisma-input.js.map +1 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/types/new-arkos-config.js.map +1 -1
- package/dist/cjs/types/router-config.js.map +1 -1
- package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js +86 -28
- package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js +11 -7
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/upload-config.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +34 -28
- package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js +9 -6
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js +334 -77
- package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
- package/dist/cjs/utils/bundler.js.map +1 -1
- package/dist/cjs/utils/cli/build.js +2 -3
- package/dist/cjs/utils/cli/build.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +11 -6
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/export-auth-action.js +5 -4
- package/dist/cjs/utils/cli/export-auth-action.js.map +1 -1
- package/dist/cjs/utils/cli/generate.js +6 -8
- package/dist/cjs/utils/cli/generate.js.map +1 -1
- package/dist/cjs/utils/cli/index.js +22 -19
- package/dist/cjs/utils/cli/index.js.map +1 -1
- package/dist/cjs/utils/cli/start.js +4 -2
- package/dist/cjs/utils/cli/start.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 +19 -7
- 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 +7 -6
- package/dist/cjs/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/policy-template.js +4 -4
- package/dist/cjs/utils/cli/utils/template-generator/templates/policy-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generators.js +0 -6
- package/dist/cjs/utils/cli/utils/template-generators.js.map +1 -1
- package/dist/cjs/utils/define-config.js +5 -0
- package/dist/cjs/utils/define-config.js.map +1 -1
- package/dist/cjs/utils/dotenv.helpers.js +0 -6
- package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
- package/dist/cjs/utils/features/api.features.js +23 -5
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/cjs/utils/helpers/arkos-config.helpers.js +22 -2
- package/dist/cjs/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/exit-error.js +1 -0
- package/dist/cjs/utils/helpers/exit-error.js.map +1 -1
- package/dist/cjs/utils/helpers/fs.helpers.js +25 -24
- package/dist/cjs/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/global.helpers.js +3 -2
- package/dist/cjs/utils/helpers/global.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js +4 -5
- package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/url-helpers.js +14 -0
- package/dist/cjs/utils/helpers/url-helpers.js.map +1 -0
- package/dist/cjs/utils/initialize-app.js +35 -6
- package/dist/cjs/utils/initialize-app.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +12 -6
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-schema-parser.js +10 -3
- package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/cjs/utils/setup-app.js +58 -41
- package/dist/cjs/utils/setup-app.js.map +1 -1
- package/dist/esm/app.js +6 -0
- package/dist/esm/app.js.map +1 -1
- package/dist/esm/exports/error-handler/index.js +1 -0
- package/dist/esm/exports/error-handler/index.js.map +1 -1
- package/dist/esm/modules/auth/auth.router.js +3 -0
- package/dist/esm/modules/auth/auth.router.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +2 -0
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/base/base.controller.js +15 -3
- package/dist/esm/modules/base/base.controller.js.map +1 -1
- package/dist/esm/modules/base/base.middlewares.js +19 -12
- package/dist/esm/modules/base/base.middlewares.js.map +1 -1
- package/dist/esm/modules/base/base.service.js +5 -1
- package/dist/esm/modules/base/base.service.js.map +1 -1
- package/dist/esm/modules/base/utils/helpers/base.service.helpers.js +9 -0
- package/dist/esm/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +22 -42
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/app-error.js +0 -1
- package/dist/esm/modules/error-handler/utils/app-error.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +8 -9
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.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 +10 -14
- package/dist/esm/modules/file-upload/file-upload.controller.js.map +1 -1
- package/dist/esm/modules/file-upload/file-upload.router.js +2 -0
- package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
- package/dist/esm/modules/swagger/swagger.router.js +8 -2
- package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
- package/dist/esm/modules/swagger/utils/get-open-api-login-html.js +18 -0
- package/dist/esm/modules/swagger/utils/get-open-api-login-html.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/get-swagger-default-configs.js +5 -5
- package/dist/esm/modules/swagger/utils/helpers/get-swagger-default-configs.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js +1 -1
- package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
- package/dist/esm/types/arkos-prisma-input.js.map +1 -1
- package/dist/esm/types/index.js.map +1 -1
- package/dist/esm/types/new-arkos-config.js.map +1 -1
- package/dist/esm/types/router-config.js.map +1 -1
- package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js +86 -28
- package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js +11 -7
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/upload-config.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +34 -28
- package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/index.js +9 -6
- package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js +334 -77
- package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
- package/dist/esm/utils/bundler.js.map +1 -1
- package/dist/esm/utils/cli/build.js +3 -4
- package/dist/esm/utils/cli/build.js.map +1 -1
- package/dist/esm/utils/cli/dev.js +12 -7
- package/dist/esm/utils/cli/dev.js.map +1 -1
- package/dist/esm/utils/cli/export-auth-action.js +5 -4
- package/dist/esm/utils/cli/export-auth-action.js.map +1 -1
- package/dist/esm/utils/cli/generate.js +6 -8
- package/dist/esm/utils/cli/generate.js.map +1 -1
- package/dist/esm/utils/cli/index.js +22 -19
- package/dist/esm/utils/cli/index.js.map +1 -1
- package/dist/esm/utils/cli/start.js +4 -2
- package/dist/esm/utils/cli/start.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 +16 -7
- 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 +7 -6
- package/dist/esm/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/policy-template.js +4 -4
- package/dist/esm/utils/cli/utils/template-generator/templates/policy-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generators.js +0 -6
- package/dist/esm/utils/cli/utils/template-generators.js.map +1 -1
- package/dist/esm/utils/define-config.js +5 -0
- package/dist/esm/utils/define-config.js.map +1 -1
- package/dist/esm/utils/dotenv.helpers.js +0 -6
- package/dist/esm/utils/dotenv.helpers.js.map +1 -1
- package/dist/esm/utils/features/api.features.js +23 -5
- package/dist/esm/utils/features/api.features.js.map +1 -1
- package/dist/esm/utils/helpers/arkos-config.helpers.js +20 -2
- package/dist/esm/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/exit-error.js +1 -0
- package/dist/esm/utils/helpers/exit-error.js.map +1 -1
- package/dist/esm/utils/helpers/fs.helpers.js +25 -24
- package/dist/esm/utils/helpers/fs.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/global.helpers.js +1 -1
- package/dist/esm/utils/helpers/global.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/prisma.helpers.js +4 -5
- package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/url-helpers.js +11 -0
- package/dist/esm/utils/helpers/url-helpers.js.map +1 -0
- package/dist/esm/utils/initialize-app.js +35 -6
- package/dist/esm/utils/initialize-app.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js +12 -6
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-schema-parser.js +10 -3
- package/dist/esm/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/esm/utils/setup-app.js +59 -42
- package/dist/esm/utils/setup-app.js.map +1 -1
- package/dist/types/app.d.ts +5 -6
- package/dist/types/exports/error-handler/index.d.ts +1 -0
- package/dist/types/modules/auth/auth.service.d.ts +2 -6
- package/dist/types/modules/base/base.service.d.ts +2 -1
- package/dist/types/modules/error-handler/utils/app-error.d.ts +0 -2
- package/dist/types/modules/error-handler/utils/error-handler.helpers.d.ts +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/modules/swagger/utils/helpers/get-swagger-default-configs.d.ts +48 -2
- package/dist/types/types/arkos-prisma-input.d.ts +3 -2
- package/dist/types/types/index.d.ts +0 -21
- package/dist/types/types/new-arkos-config.d.ts +183 -14
- package/dist/types/types/router-config.d.ts +1 -1
- package/dist/types/utils/arkos-router/arkos-router-openapi-manager.d.ts +14 -1
- package/dist/types/utils/arkos-router/index.d.ts +76 -8
- package/dist/types/utils/arkos-router/types/index.d.ts +19 -6
- package/dist/types/utils/arkos-router/types/upload-config.d.ts +63 -7
- package/dist/types/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.d.ts +1 -1
- package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +2 -0
- package/dist/types/utils/arkos-router/utils/helpers/upload-manager.d.ts +0 -36
- package/dist/types/utils/bundler.d.ts +1 -1
- package/dist/types/utils/cli/generate.d.ts +0 -1
- package/dist/types/utils/cli/start.d.ts +1 -1
- package/dist/types/utils/helpers/arkos-config.helpers.d.ts +2 -0
- package/dist/types/utils/helpers/fs.helpers.d.ts +1 -1
- package/dist/types/utils/helpers/global.helpers.d.ts +1 -0
- package/dist/types/utils/helpers/url-helpers.d.ts +1 -0
- package/dist/types/utils/prisma/prisma-schema-parser.d.ts +1 -0
- package/package.json +15 -15
- package/dist/cjs/utils/cli/utils/template-generator/templates/route-hook.template.js +0 -39
- package/dist/cjs/utils/cli/utils/template-generator/templates/route-hook.template.js.map +0 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/service-hook.template.js +0 -32
- package/dist/cjs/utils/cli/utils/template-generator/templates/service-hook.template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/route-hook.template.js +0 -36
- package/dist/esm/utils/cli/utils/template-generator/templates/route-hook.template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/service-hook.template.js +0 -29
- package/dist/esm/utils/cli/utils/template-generator/templates/service-hook.template.js.map +0 -1
- package/dist/types/utils/cli/utils/template-generator/templates/route-hook.template.d.ts +0 -2
- package/dist/types/utils/cli/utils/template-generator/templates/service-hook.template.d.ts +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AAGA,wCAEC;AAED,4CAEC;AAED,
|
|
1
|
+
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"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AAQ,CACjB,OAAO,EACP,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EACjB,GAAG,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,IAAA,gCAAU,EAAC,KAAK,IAAI,EAAE,CAAC,gBAAgB,CACnE,CAAC;AACJ,CAAC;AAED,SAAgB,qCAAqC,CAAC,CAAM;IAC1D,OAAO,IAAI,mBAAQ,CACjB,iCAAiC,EACjC,GAAG,EACH,oBAAoB,EACpB,EAAE,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { pascalCase } from \"../../../utils/helpers/change-case.helpers\";\nimport AppError from \"./app-error\";\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 =\n err?.message?.split(\"\\n\")[err?.message?.split(\"\\n\").length - 1] ||\n \"Invalid query arguments\";\n return new AppError(\n message.split(\". Did you\")[0],\n 400,\n \"InvalidQueryArgument\"\n );\n}\n\nexport function handleAuthenticationError(_: 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(_: 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(_: 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(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\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(_: 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: any) {\n const field = err?.meta?.target || \"unknown\";\n const message = `Duplicate unique field(s) ${Array.isArray(field) ? field.map((f) => `'${f}'`).join(\", \") : `'${field}'`}`;\n return new AppError(message, 409, \"DuplicateRecords\");\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 409, \"ForeignKeyViolation\");\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 handleSchemaCreationFailedError(_: 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(_: 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 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 some required record was not found`;\n\n const model = err?.meta?.cause\n ? err?.meta?.cause?.split(\"No '\")?.[1]?.split?.(\"'\")?.[0]\n : \"\";\n\n return new AppError(\n message,\n model ? 400 : 404,\n `${model ? \"Inline\" : \"\"}${pascalCase(model || \"\")}RecordNotFound`\n );\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n \"ServiceUnavailable\",\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,IAAI,GAAG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,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"]}
|
|
@@ -11,10 +11,13 @@ const fs_1 = __importDefault(require("fs"));
|
|
|
11
11
|
const catch_async_1 = __importDefault(require("../error-handler/utils/catch-async.js"));
|
|
12
12
|
const server_1 = require("../../server.js");
|
|
13
13
|
const file_upload_helpers_1 = require("./utils/helpers/file-upload.helpers.js");
|
|
14
|
-
const multer_1 = require("multer");
|
|
15
|
-
const utils_1 = require("../../exports/utils/index.js");
|
|
16
14
|
const arkos_loadable_registry_1 = __importDefault(require("../../components/arkos-loadable-registry/index.js"));
|
|
17
15
|
const reader_1 = require("../../components/arkos-route-hook/reader.js");
|
|
16
|
+
function matchesUploadUrl(originalUrl, baseUploadRoute, fileType, fileName) {
|
|
17
|
+
const expectedPath = `${baseUploadRoute}/${fileType}/${fileName}`;
|
|
18
|
+
return ((originalUrl === expectedPath || originalUrl.startsWith(expectedPath)) &&
|
|
19
|
+
new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`).test(originalUrl));
|
|
20
|
+
}
|
|
18
21
|
class FileUploadController {
|
|
19
22
|
constructor() {
|
|
20
23
|
this.uploadFile = (0, catch_async_1.default)(async (req, res, next) => {
|
|
@@ -50,7 +53,7 @@ class FileUploadController {
|
|
|
50
53
|
}
|
|
51
54
|
uploader.handleMultipleUpload()(req, res, async (err) => {
|
|
52
55
|
if (err)
|
|
53
|
-
|
|
56
|
+
throw err;
|
|
54
57
|
let data;
|
|
55
58
|
if (req.files && Array.isArray(req.files) && req.files.length > 0) {
|
|
56
59
|
if (fileType === "images") {
|
|
@@ -112,10 +115,11 @@ class FileUploadController {
|
|
|
112
115
|
default:
|
|
113
116
|
return next(new app_error_1.default("Invalid file type", 400, "InvalidFileType"));
|
|
114
117
|
}
|
|
118
|
+
const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
115
119
|
try {
|
|
116
120
|
const { fileUpload } = (0, server_1.getArkosConfig)();
|
|
117
121
|
const baseUploadRoute = fileUpload?.baseRoute || "/api/uploads";
|
|
118
|
-
const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
|
|
122
|
+
const urlPattern = new RegExp(`${escapeRegExp(baseUploadRoute)}/${escapeRegExp(fileType)}/${escapeRegExp(fileName)}`);
|
|
119
123
|
const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
|
|
120
124
|
if (isExpectedUrlPattern) {
|
|
121
125
|
const fullUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
|
|
@@ -170,15 +174,13 @@ class FileUploadController {
|
|
|
170
174
|
}
|
|
171
175
|
uploader.handleMultipleUpload()(req, res, async (err) => {
|
|
172
176
|
if (err)
|
|
173
|
-
|
|
177
|
+
throw err;
|
|
174
178
|
if (!req.file &&
|
|
175
179
|
(!req.files || !Array.isArray(req.files) || req.files.length === 0))
|
|
176
180
|
return next(new app_error_1.default("No new file uploaded", 400, "MissingNewFile"));
|
|
177
181
|
if (fileName && fileName.trim() !== "") {
|
|
178
182
|
try {
|
|
179
|
-
const
|
|
180
|
-
const urlPattern = new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`);
|
|
181
|
-
const isExpectedUrlPattern = urlPattern.test(req.originalUrl);
|
|
183
|
+
const isExpectedUrlPattern = matchesUploadUrl(req.originalUrl, fileUpload?.baseRoute || "/api/uploads", fileType, fileName);
|
|
182
184
|
if (isExpectedUrlPattern) {
|
|
183
185
|
const oldFileUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`;
|
|
184
186
|
await uploader.deleteFileByUrl(oldFileUrl);
|
|
@@ -234,12 +236,6 @@ class FileUploadController {
|
|
|
234
236
|
});
|
|
235
237
|
});
|
|
236
238
|
}
|
|
237
|
-
handleUploadError(err, next) {
|
|
238
|
-
if (err instanceof multer_1.MulterError)
|
|
239
|
-
return next(new app_error_1.default(err.message, 400, (0, utils_1.pascalCase)(err.code || "FileUploadError")));
|
|
240
|
-
else
|
|
241
|
-
return next(err);
|
|
242
|
-
}
|
|
243
239
|
getRouteHook() {
|
|
244
240
|
return arkos_loadable_registry_1.default.getItem("ArkosRouteHook", "file-upload");
|
|
245
241
|
}
|
|
@@ -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,m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W,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;IACJ,CAAC;IAzUS,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;IAEO,YAAY;QAClB,OAAO,iCAAgB,CAAC,OAAO,CAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC;IACnE,CAAC;IAEO,YAAY,CAAC,SAAiB;QACpC,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QACjC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,OAAO,CACL,wBAAe,CAAC,QAAQ,CAAC,aAAa,EAAE,SAAgB,CAAC,EAAE,KAAK,IAAI,IAAI,CACzE,CAAC;IACJ,CAAC;CAmTF;AA1UD,oDA0UC;AAaD,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 { MulterError } from \"multer\";\nimport { pascalCase } from \"../../exports/utils\";\nimport loadableRegistry from \"../../components/arkos-loadable-registry\";\nimport { routeHookReader } from \"../../components/arkos-route-hook/reader\";\n\n/**\n * Handles file uploads and allows to be extended via route hooks.\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 private getRouteHook() {\n return loadableRegistry.getItem(\"ArkosRouteHook\", \"file-upload\");\n }\n\n private getAfterHook(operation: string) {\n const hook = this.getRouteHook();\n if (!hook) return null;\n return (\n routeHookReader.getHooks(\"file-upload\", operation as any)?.after ?? null\n );\n }\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs.\n *\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 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 {\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 = req.files.map((file) => processFile(req, file.path));\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 = 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 const afterHook = this.getAfterHook(\"uploadFile\");\n if (afterHook) {\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 * @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 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 const fullUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n const afterHook = this.getAfterHook(\"deleteFile\");\n if (afterHook) {\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 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 *\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 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 {\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 const urlPattern = new RegExp(\n `${baseUploadRoute}/${fileType}/${fileName}`\n );\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\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 = req.files.map((file) => processFile(req, file.path));\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 = 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 const afterHook = this.getAfterHook(\"updateFile\");\n if (afterHook) {\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/**\n * Controller instance responsible for handling file upload operations.\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/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,uGAAwE;AACxE,qEAA2E;AAE3E,SAAS,gBAAgB,CACvB,WAAmB,EACnB,eAAuB,EACvB,QAAgB,EAChB,QAAgB;IAEhB,MAAM,YAAY,GAAG,GAAG,eAAe,IAAI,QAAQ,IAAI,QAAQ,EAAE,CAAC;IAClE,OAAO,CACL,CAAC,WAAW,KAAK,YAAY,IAAI,WAAW,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;QACtE,IAAI,MAAM,CAAC,GAAG,eAAe,IAAI,QAAQ,IAAI,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAC3E,CAAC;AACJ,CAAC;AAKD,MAAa,oBAAoB;IAAjC;QAoBE,eAAU,GAAG,IAAA,qBAAU,EACrB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;YAChC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;YACtD,MAAM,OAAO,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;YAEpD,MAAM,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,GAAG,IAAA,2CAAqB,GAAE,CAAC;YAE5B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GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QACjC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,OAAO,CACL,wBAAe,CAAC,QAAQ,CAAC,aAAa,EAAE,SAAgB,CAAC,EAAE,KAAK,IAAI,IAAI,CACzE,CAAC;IACJ,CAAC;CAsTF;AAjUD,oDAiUC;AAaD,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 loadableRegistry from \"../../components/arkos-loadable-registry\";\nimport { routeHookReader } from \"../../components/arkos-route-hook/reader\";\n\nfunction matchesUploadUrl(\n originalUrl: string,\n baseUploadRoute: string,\n fileType: string,\n fileName: string\n): boolean {\n const expectedPath = `${baseUploadRoute}/${fileType}/${fileName}`;\n return (\n (originalUrl === expectedPath || originalUrl.startsWith(expectedPath)) &&\n new RegExp(`${baseUploadRoute}/${fileType}/${fileName}`).test(originalUrl)\n );\n}\n\n/**\n * Handles file uploads and allows to be extended via route hooks.\n */\nexport class FileUploadController {\n private getRouteHook() {\n return loadableRegistry.getItem(\"ArkosRouteHook\", \"file-upload\");\n }\n\n private getAfterHook(operation: string) {\n const hook = this.getRouteHook();\n if (!hook) return null;\n return (\n routeHookReader.getHooks(\"file-upload\", operation as any)?.after ?? null\n );\n }\n\n /**\n * Handles file upload requests, processes images if needed, and returns URLs.\n *\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 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 {\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 = req.files.map((file) => processFile(req, file.path));\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 = 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 const afterHook = this.getAfterHook(\"uploadFile\");\n if (afterHook) {\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 * @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 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 // top of file or a shared utils import\n const escapeRegExp = (value: string) =>\n value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n try {\n const { fileUpload } = getArkosConfig();\n\n const baseUploadRoute = fileUpload?.baseRoute || \"/api/uploads\";\n const urlPattern = new RegExp(\n `${escapeRegExp(baseUploadRoute)}/${escapeRegExp(fileType)}/${escapeRegExp(fileName)}`\n );\n\n const isExpectedUrlPattern = urlPattern.test(req.originalUrl);\n if (isExpectedUrlPattern) {\n const fullUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\n await uploader.deleteFileByUrl(fullUrl);\n } else {\n await uploader.deleteFileByName(fileName, fileType);\n }\n\n const afterHook = this.getAfterHook(\"deleteFile\");\n if (afterHook) {\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 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 *\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 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 {\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 isExpectedUrlPattern = matchesUploadUrl(\n req.originalUrl,\n fileUpload?.baseRoute || \"/api/uploads\",\n fileType,\n fileName\n );\n\n if (isExpectedUrlPattern) {\n const oldFileUrl = `${req.protocol}://${req.get(\"host\")}${req.originalUrl}`;\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 = req.files.map((file) => processFile(req, file.path));\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 = 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 const afterHook = this.getAfterHook(\"updateFile\");\n if (afterHook) {\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/**\n * Controller instance responsible for handling file upload operations.\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/reference/file-upload-controller-object}\n */\nconst fileUploadController = new FileUploadController();\n\nexport default fileUploadController;\n"]}
|
|
@@ -19,6 +19,8 @@ const file_upload_json_schema_generator_1 = __importDefault(require("./utils/fil
|
|
|
19
19
|
function getFileUploadRouter() {
|
|
20
20
|
const router = (0, arkos_router_1.default)();
|
|
21
21
|
const { fileUpload } = (0, server_1.getArkosConfig)();
|
|
22
|
+
if (!fileUpload?.enabled === false)
|
|
23
|
+
return router;
|
|
22
24
|
const routeHook = arkos_loadable_registry_1.default.getItem("ArkosRouteHook", "file-upload");
|
|
23
25
|
const op = (operation) => {
|
|
24
26
|
let components = routeHook
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AAgBA,
|
|
1
|
+
{"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AAgBA,kDA6HC;AA7ID,sFAA4D;AAC5D,sDAA8B;AAC9B,4FAA6D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AC,EAC3B,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,OAAO,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACjD,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import fileUploadController from \"./file-upload.controller\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { sendResponse } from \"../base/base.middlewares\";\nimport { processMiddleware } from \"../../utils/helpers/routers.helpers\";\nimport { adjustRequestUrl } from \"./utils/helpers/file-upload.helpers\";\nimport path from \"path\";\nimport ArkosRouter from \"../../utils/arkos-router\";\nimport loadableRegistry from \"../../components/arkos-loadable-registry\";\nimport {\n OperationByModule,\n routeHookReader,\n} from \"../../components/arkos-route-hook/reader\";\nimport { getArkosConfig } from \"../../server\";\nimport fileUploadJsonSchemaGenerator from \"./utils/file-upload-json-schema-generator\";\n\nexport function getFileUploadRouter() {\n const router = ArkosRouter();\n const { fileUpload } = getArkosConfig();\n if (!fileUpload?.enabled === false) return router;\n\n const routeHook = loadableRegistry.getItem(\"ArkosRouteHook\", \"file-upload\");\n\n const op = (operation: OperationByModule<\"file-upload\">) => {\n let components = routeHook\n ? routeHookReader.forOperation(\"file-upload\", operation)\n : {\n before: [],\n after: [],\n onError: [],\n routeConfig: {},\n };\n\n let endpointConfig = components.routeConfig || {};\n if (endpointConfig?.experimental?.openapi !== false)\n endpointConfig = {\n ...(endpointConfig || {}),\n experimental: {\n ...(endpointConfig?.experimental || {}),\n openapi: fileUploadJsonSchemaGenerator.getOpenApiConfig(\n endpointConfig,\n operation\n ),\n },\n };\n\n components.routeConfig = endpointConfig;\n return components;\n };\n\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n // FIND FILE\n {\n const { before, onError, routeConfig } = op(\"findFile\");\n const baseUploadDirFullPath = path.resolve(\n path\n .join(process.cwd(), fileUpload?.baseUploadDir || \"uploads\")\n .replaceAll(\"//\", \"/\")\n );\n router.get(\n {\n authentication: { action: \"View\", resource: \"file-upload\" },\n ...routeConfig,\n path: `${basePathname}*`,\n },\n ...processMiddleware(before),\n adjustRequestUrl,\n express.static(\n baseUploadDirFullPath,\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStatic || {}\n )\n ),\n ...processMiddleware(onError, { type: \"error\" })\n );\n }\n\n // UPLOAD FILE\n {\n const { before, after, onError, routeConfig } = op(\"uploadFile\");\n router.post(\n {\n authentication: { action: \"Create\", resource: \"file-upload\" },\n ...routeConfig,\n path: `${basePathname}:fileType`,\n },\n ...processMiddleware(before),\n fileUploadController.uploadFile,\n ...processMiddleware(after),\n sendResponse,\n ...processMiddleware(onError, { type: \"error\" })\n );\n }\n\n // UPDATE FILE\n {\n const { before, after, onError, routeConfig } = op(\"updateFile\");\n router.patch(\n {\n authentication: { action: \"Update\", resource: \"file-upload\" },\n ...routeConfig,\n path: `${basePathname}:fileType/:fileName`,\n },\n ...processMiddleware(before),\n fileUploadController.updateFile,\n ...processMiddleware(after),\n sendResponse,\n ...processMiddleware(onError, { type: \"error\" })\n );\n }\n\n // DELETE FILE\n {\n const { before, after, onError, routeConfig } = op(\"deleteFile\");\n router.delete(\n {\n authentication: { action: \"Delete\", resource: \"file-upload\" },\n ...routeConfig,\n path: `${basePathname}:fileType/:fileName`,\n },\n ...processMiddleware(before),\n fileUploadController.deleteFile,\n ...processMiddleware(after),\n sendResponse,\n ...processMiddleware(onError, { type: \"error\" })\n );\n }\n\n return router;\n}\n"]}
|
|
@@ -17,9 +17,15 @@ const get_open_api_login_html_1 = __importDefault(require("./utils/get-open-api-
|
|
|
17
17
|
const swaggerRouter = (0, express_1.Router)();
|
|
18
18
|
function getSwaggerRouter(arkosConfig, app) {
|
|
19
19
|
const pathsFromCustomArkosRouters = (0, arkos_router_1.generateOpenAPIFromApp)(app);
|
|
20
|
-
const
|
|
20
|
+
const defaultSwaggerConfig = (0, get_swagger_default_configs_1.default)({
|
|
21
21
|
...pathsFromCustomArkosRouters,
|
|
22
|
-
})
|
|
22
|
+
});
|
|
23
|
+
const swaggerConfigs = (0, deepmerge_helper_1.default)(defaultSwaggerConfig, arkosConfig.swagger || {});
|
|
24
|
+
if (arkosConfig.swagger?.options?.definition?.servers && swaggerConfigs) {
|
|
25
|
+
swaggerConfigs.options.definition.servers =
|
|
26
|
+
arkosConfig.swagger.options.definition.servers;
|
|
27
|
+
swaggerConfigs.options.definition.servers.push(defaultSwaggerConfig.options.definition.servers[0]);
|
|
28
|
+
}
|
|
23
29
|
const { definition, ...options } = swaggerConfigs?.options;
|
|
24
30
|
const swaggerSpecification = (0, swagger_jsdoc_1.default)({
|
|
25
31
|
definition: definition,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAoBA,
|
|
1
|
+
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAoBA,4CAgGC;AAED,4CA2BC;AAjJD,qCAAiC;AACjC,kEAAyC;AACzC,8GAAkF;AAClF,uEAAyF;AACzF,2DAAkE;AAOlE,4FAA6D;AAG7D,wEAA+C;AAC/C,iFAAwD;AACxD,8FAAkE;AAElE,MAAM,aAAa,GAAG,IAAA,gBAAM,GAAE,CAAC;AAE/B,SAAgB,gBAAgB,CAC9B,WAA4B,EAC5B,GAAU;IAEV,MAAM,2BAA2B,GAAG,IAAA,qCAAsB,EAAC,GAAG,CAAC,CAAC;IAChE,MAAM,oBAAoB,GAAG,IAAA,qCAAuB,EAAC;QACnD,GAAG,2BAA2B;KAC/B,CAAE,CAAC;IAEJ,MAAM,cAAc,G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a,EAAE,CAAC;YACnB,IAAI,CAAC,aAAa,EAAE,CAAC;gBACnB,aAAa,GAAG,IAAA,oDAAmC,EACjD,+BAA+B,CAChC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;oBAChB,aAAa,GAAG,MAAM,CAAC,YAAY,CAAC;wBAClC,OAAO,EAAE,oBAAoB;wBAC7B,GAAG,cAAc,EAAE,+BAA+B;qBACnD,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;YACL,CAAC;YACD,MAAM,aAAa,CAAC;QACtB,CAAC;QACD,OAAO,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { Router } from \"express\";\nimport swaggerJsdoc from \"swagger-jsdoc\";\nimport getSwaggerDefaultConfig from \"./utils/helpers/get-swagger-default-configs\";\nimport { importEsmPreventingTsTransformation } from \"../../utils/helpers/global.helpers\";\nimport { generateOpenAPIFromApp } from \"../../utils/arkos-router\";\nimport {\n ArkosConfig,\n ArkosNextFunction,\n ArkosRequest,\n ArkosResponse,\n} from \"../../exports\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { Arkos } from \"../../types/arkos\";\nimport { UserArkosConfig } from \"../../utils/define-config\";\nimport authService from \"../auth/auth.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport getOpenApiLoginHtml from \"./utils/get-open-api-login-html\";\n\nconst swaggerRouter = Router();\n\nexport function getSwaggerRouter(\n arkosConfig: UserArkosConfig,\n app: Arkos\n): Router {\n const pathsFromCustomArkosRouters = generateOpenAPIFromApp(app);\n const defaultSwaggerConfig = getSwaggerDefaultConfig({\n ...pathsFromCustomArkosRouters,\n })!;\n\n const swaggerConfigs = deepmerge(\n defaultSwaggerConfig,\n arkosConfig.swagger || {}\n ) as ArkosConfig[\"swagger\"];\n\n if (arkosConfig.swagger?.options?.definition?.servers && swaggerConfigs) {\n swaggerConfigs!.options!.definition!.servers =\n arkosConfig.swagger.options.definition.servers;\n\n swaggerConfigs!.options!.definition!.servers.push(\n defaultSwaggerConfig.options.definition.servers[0]\n );\n }\n\n const { definition, ...options } = swaggerConfigs?.options!;\n const swaggerSpecification = swaggerJsdoc({\n definition: definition as swaggerJsdoc.SwaggerDefinition,\n ...options,\n });\n\n const endpoint = swaggerConfigs!.endpoint!;\n\n const swaggerAuth = arkosConfig?.swagger;\n const authenticate = swaggerAuth?.authenticate !== false;\n\n if (authenticate) {\n swaggerRouter.use(\n endpoint,\n (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.path.includes(\"/auth\")) return next();\n next(\"route\"); // skip to auth chain below\n }\n );\n\n swaggerRouter.use(\n endpoint,\n authService.authenticate,\n (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (!req.user?.isSuperUser)\n return next(\n new AppError(\n \"Only super users can access API documentation in production.\",\n 403,\n \"SuperUserRequired\"\n )\n );\n next();\n },\n (\n err: AppError,\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (req.path.includes(\"/auth\")) return next();\n const message = encodeURIComponent(\n err?.message || \"Authentication required.\"\n );\n return res.redirect(\n `${arkosConfig.globalPrefix}${endpoint}/auth/login?error-message=${message}`\n );\n }\n );\n }\n\n swaggerRouter.get(\n `${endpoint}/auth/login`,\n (_: ArkosRequest, res: ArkosResponse) => {\n res.send(getOpenApiLoginHtml());\n }\n );\n\n swaggerRouter.get(\n `${endpoint}/openapi.json`,\n (_: ArkosRequest, res: ArkosResponse) => {\n res.json(swaggerSpecification);\n }\n );\n\n let scalarHandler: any = null;\n\n swaggerRouter.use(\n endpoint,\n scalarMiddleware(scalarHandler, swaggerSpecification, swaggerConfigs)\n );\n\n return swaggerRouter;\n}\n\nexport function scalarMiddleware(\n scalarHandler: any,\n swaggerSpecification: object,\n swaggerConfigs: any\n) {\n let scalarLoading: Promise<void> | null = null;\n\n return async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (!scalarHandler) {\n if (!scalarLoading) {\n scalarLoading = importEsmPreventingTsTransformation(\n \"@scalar/express-api-reference\"\n ).then((scalar) => {\n scalarHandler = scalar.apiReference({\n content: swaggerSpecification,\n ...swaggerConfigs?.scalarApiReferenceConfiguration,\n });\n });\n }\n await scalarLoading;\n }\n return scalarHandler(req, res, next);\n };\n}\n"]}
|
|
@@ -162,6 +162,20 @@ function getOpenApiLoginHtml() {
|
|
|
162
162
|
}
|
|
163
163
|
|
|
164
164
|
.error-message.show { display: block; }
|
|
165
|
+
|
|
166
|
+
.page-footer {
|
|
167
|
+
position: fixed;
|
|
168
|
+
bottom: 16px;
|
|
169
|
+
width: 100%;
|
|
170
|
+
text-align: center;
|
|
171
|
+
font-size: 14px;
|
|
172
|
+
color: #999999;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
.page-footer a {
|
|
176
|
+
color: #999999;
|
|
177
|
+
text-decoration: underline;
|
|
178
|
+
}
|
|
165
179
|
</style>
|
|
166
180
|
</head>
|
|
167
181
|
<body>
|
|
@@ -211,6 +225,10 @@ function getOpenApiLoginHtml() {
|
|
|
211
225
|
</form>
|
|
212
226
|
</div>
|
|
213
227
|
|
|
228
|
+
<footer class="page-footer">
|
|
229
|
+
Powered by <a href="https://www.arkosjs.com" target="_blank" rel="noopener noreferrer">Arkos.js</a>
|
|
230
|
+
</footer>
|
|
231
|
+
|
|
214
232
|
<script>
|
|
215
233
|
const usernameLabel = document.getElementById('usernameLabel');
|
|
216
234
|
const usernameField = document.getElementById('usernameField');
|