arkos 1.1.62-test → 1.1.64-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 +1 -1
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/modules/auth/auth.router.js +6 -1
- package/dist/cjs/modules/auth/auth.router.js.map +1 -1
- package/dist/cjs/modules/base/base.controller.js +3 -3
- package/dist/cjs/modules/base/base.controller.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +0 -139
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/types/arkos-config.js.map +1 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/es2020/app.js +1 -1
- package/dist/es2020/app.js.map +1 -1
- package/dist/es2020/modules/auth/auth.router.js +6 -1
- package/dist/es2020/modules/auth/auth.router.js.map +1 -1
- package/dist/es2020/modules/base/base.controller.js +3 -3
- package/dist/es2020/modules/base/base.controller.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/es2020/modules/error-handler/error-handler.controller.js +1 -1
- package/dist/es2020/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/es2020/modules/swagger/swagger.router.js +1 -134
- package/dist/es2020/modules/swagger/swagger.router.js.map +1 -1
- package/dist/es2020/types/arkos-config.js.map +1 -1
- package/dist/es2020/types/index.js.map +1 -1
- package/dist/types/modules/swagger/swagger.router.d.ts +0 -3
- package/dist/types/types/arkos-config.d.ts +1 -43
- package/dist/types/types/index.d.ts +1 -1
- package/package.json +3 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n /**\n * Defines allowed origins to acess the API.\n */\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * })\n * ```\n *\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod`\": Uses OpenAPI-compliant schemas directly\n * - \"json-schema\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\" | \"json-schema\";\n /**\n *\n */\n options: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Local server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description: string;\n }[];\n\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Custom Swagger UI options.\n *\n * See: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md\n */\n swaggerUiOptions?: Record<string, any>;\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AA6EA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nexport type PrismaOperations = \"findMany\";\n\nexport type PrismaQueryOptions<T extends Record<string, any>> = {\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n};\n\nexport type AuthPrismaQueryOptions<T extends Record<string, any>> = {\n // User profile endpoints\n getMe?: Partial<Parameters<T[\"findUnique\"]>[0]>;\n updateMe?: Partial<Parameters<T[\"update\"]>[0]>;\n deleteMe?: Partial<Parameters<T[\"update\"]>[0]>;\n\n // Authentication endpoints\n login?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n signup?: Partial<Parameters<T[\"create\"]>[0]>;\n updatePassword?: Partial<Parameters<T[\"update\"]>[0]>;\n};\n\n/**\n * Interface defining the minimum structure required for Prisma model delegates\n * This allows us to constraint TModel without requiring Prisma imports\n */\nexport type PrismaModelDelegate = Record<\n
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AA6EA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nexport type PrismaOperations = \"findMany\";\n\nexport type PrismaQueryOptions<T extends Record<string, any>> = {\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n};\n\nexport type AuthPrismaQueryOptions<T extends Record<string, any>> = {\n // User profile endpoints\n getMe?: Partial<Parameters<T[\"findUnique\"]>[0]>;\n updateMe?: Partial<Parameters<T[\"update\"]>[0]>;\n deleteMe?: Partial<Parameters<T[\"update\"]>[0]>;\n\n // Authentication endpoints\n login?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n signup?: Partial<Parameters<T[\"create\"]>[0]>;\n updatePassword?: Partial<Parameters<T[\"update\"]>[0]>;\n};\n\n/**\n * Interface defining the minimum structure required for Prisma model delegates\n * This allows us to constraint TModel without requiring Prisma imports\n */\nexport type PrismaModelDelegate = Record<\n any,\n (args: Record<any, never>) => any\n>;\n\ntype a = {\n create: (args: { data: never; [key: string]: never }) => Promise<any>;\n createMany: (args: { data: never; [key: string]: never }) => Promise<any>;\n findMany: (args: { [key: string]: never }) => Promise<any[]>;\n findFirst: (args: { where: never; [key: string]: never }) => Promise<any>;\n findUnique: (args: { where: never; [key: string]: never }) => Promise<any>;\n update: (args: {\n where: never;\n data: never;\n [key: string]: never;\n }) => Promise<any>;\n updateMany: (args: {\n where: never;\n data: never;\n [key: string]: never;\n }) => Promise<any>;\n delete: (args: { where: never; [key: string]: never }) => Promise<any>;\n deleteMany: (args: { where: never; [key: string]: never }) => Promise<any>;\n count: (args: { where: never; [key: string]: never }) => Promise<number>;\n};\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n Create = \"Create\",\n View = \"View\",\n Update = \"Update\",\n Delete = \"Delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface User {\n id: string;\n isStaff: boolean;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n roles?: UserRole[] | any[];\n role?: UserRole | any;\n}\n\nexport interface ArkosRequest<Body = any, Query = any> extends Request {\n user?: User & Record<string, any>;\n relationFields?: Record<string, boolean>;\n include?: Record<string, any>;\n responseData?: Record<string, any> | null | undefined;\n additionalData?: Record<string, any> | null | undefined;\n responseStatus?: number | string | null | undefined;\n body: Body;\n prismaQueryOptions?: Record<string, any>;\n // query: Query extends Request['ParsedQs'];\n}\n\nexport interface ArkosResponse extends Response {}\nexport interface ArkosNextFunction extends NextFunction {}\nexport interface ArkosRequestHandler extends RequestHandler {}\n"]}
|
package/dist/es2020/app.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import c from"express";import p from"cors";import m from"cookie-parser";import{getAuthRouter as f}from"./modules/auth/auth.router";import{getPrismaModelsRouter as w,getAvailableResourcesAndRoutesRouter as R}from"./modules/base/base.router";import
|
|
1
|
+
"use strict";import c from"express";import p from"cors";import m from"cookie-parser";import{getAuthRouter as f}from"./modules/auth/auth.router";import{getPrismaModelsRouter as w,getAvailableResourcesAndRoutesRouter as R}from"./modules/base/base.router";import h from"./modules/error-handler/error-handler.controller";import{rateLimit as P}from"express-rate-limit";import y from"compression";import{handleRequestLogs as b}from"./modules/base/base.middlewares";import{checkDatabaseConnection as q,loadPrismaModule as A}from"./utils/helpers/prisma.helpers";import{getFileUploaderRouter as E}from"./modules/file-uploader/file-uploader.router";import{queryParser as H}from"./utils/helpers/query-parser.helpers";import d from"./utils/helpers/deepmerge.helper";export const app=c();export async function bootstrap(e){await A(),e?.configureApp&&await e.configureApp(app);const n=e?.middlewares,s=n?.disable||[],t=n?.replace||{};s?.includes?.("compression")||app.use(t.compression||y(e?.compressionOptions)),s?.includes?.("global-rate-limit")||app.use(t.globalRateLimit||P(d({windowMs:60*1e3,limit:500,standardHeaders:"draft-7",legacyHeaders:!1,handler:(r,o)=>{o.status(429).json({message:"Too many requests, please try again later"})}},e?.globalRequestRateLimitOptions||{}))),s?.includes?.("cors")||app.use(t.cors||p(e?.cors?.customHandler?e.cors.customHandler:d({origin:(r,o)=>{const i=e?.cors?.allowedOrigins;i==="*"?o(null,!0):Array.isArray(i)?o(null,!r||i?.includes?.(r)):typeof i=="string"?o(null,!r||i===r):o(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},e?.cors?.options||{}))),s?.includes?.("express-json")||app.use(t.expressJson||c.json(e?.jsonBodyParserOptions)),s?.includes?.("cookie-parser")||app.use(t.cookieParser||m(...e?.cookieParserParameters||[])),s?.includes?.("query-parser")||app.use(t.queryParser||H(d({parseNull:!0,parseUndefined:!0,parseBoolean:!0},e?.queryParserOptions||{}))),s?.includes?.("database-connection")||app.use(t.databaseConnection||q),s?.includes?.("request-logger")||app.use(t.requestLogger||b),e?.middlewares?.additional&&e.middlewares.additional.forEach(r=>{app.use(r)});const l=e?.routers,u=l?.disable||[],a=l?.replace||{};if(u?.includes?.("welcome-endpoint")||app.get("/api",a.welcomeEndpoint||((r,o)=>{o.status(200).json({message:e.welcomeMessage})})),!u?.includes?.("file-uploader")){const r=a.fileUploader?await a.fileUploader(e):await E(e);app.use(r)}if(!u?.includes?.("auth-router")&&e.authentication){const r=a.authRouter?await a.authRouter(e):await f(e);app.use("/api",r)}if(!u?.includes?.("prisma-models-router")){const r=a.prismaModelsRouter?await a.prismaModelsRouter(e):await w(e);app.use("/api",r)}return app.use("/api",R()),l?.additional&&l.additional.forEach(r=>{app.use(r)}),s?.includes?.("global-error-handler")||app.use(t.globalErrorHandler||h),app}
|
package/dist/es2020/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AAErF,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAEpE,MAAM,CAAC,MAAM,GAAG,GAAoB,OAAO,EAAE,CAAC;AAE9C,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,WAAwB;IAExB,MAAM,gBAAgB,EAAE,CAAC;IAEzB,IAAI,WAAW,EAAE,YAAY;QAAE,MAAM,WAAW,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;IAEnE,MAAM,iBAAiB,GAAG,WAAW,EAAE,WAAW,CAAC;IACnD,MAAM,mBAAmB,GAAG,iBAAiB,EAAE,OAAO,IAAI,EAAE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,EAAE,CAAC,aAAa,CAAC;QAC3C,WAAW,CAAC,cAAc,EAC1B,CAAC;QACD,MAAM,UAAU,GAAG,eAAe,CAAC,UAAU;YAC3C,CAAC,CAAC,MAAM,eAAe,CAAC,UAAU,CAAC,WAAW,CAAC;YAC/C,CAAC,CAAC,MAAM,aAAa,CAAC,WAAW,CAAC,CAAC;QACrC,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IAC9B,CAAC;IAGD,IAAI,CAAC,eAAe,EAAE,QAAQ,EAAE,CAAC,sBAAsB,CAAC,EAAE,CAAC;QACzD,MAAM,YAAY,GAAG,eAAe,CAAC,kBAAkB;YACrD,CAAC,CAAC,MAAM,eAAe,CAAC,kBAAkB,CAAC,WAAW,CAAC;YACvD,CAAC,CAAC,MAAM,qBAAqB,CAAC,WAAW,CAAC,CAAC;QAC7C,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAChC,CAAC;IAED,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAExD,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC;IAG/C,IAAI,aAAa,EAAE,UAAU,EAAE,CAAC;QAC9B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAGD,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,sBAAsB,CAAC;QAC1D,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,YAAY,CAAC,CAAC;IAElE,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import express 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 {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } from \"./modules/file-uploader/file-uploader.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n 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 {\n 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 arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters?.includes?.(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(fileUploaderRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n app.use(\"/api\", getSwaggerRouter(arkosConfig));\n\n // Additional custom routers\n if (routersConfig?.additional) {\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,uBA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;QAC7C,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAChC,CAAC;IAED,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAGxD,IAAI,aAAa,EAAE,UAAU,EAAE,CAAC;QAC9B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAGD,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,sBAAsB,CAAC;QAC1D,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,YAAY,CAAC,CAAC;IAElE,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import express 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 {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } from \"./modules/file-uploader/file-uploader.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (req, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n 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 {\n 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 arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters?.includes?.(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(fileUploaderRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n // Additional custom routers\n if (routersConfig?.additional) {\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
|
|
@@ -35,11 +35,16 @@ export async function getAuthRouter(arkosConfigs) {
|
|
|
35
35
|
: middlewares?.afterDeleteMe || sendResponse, middlewares?.beforeDeleteMe && middlewares?.afterDeleteMe
|
|
36
36
|
? middlewares?.afterDeleteMe
|
|
37
37
|
: sendResponse, sendResponse);
|
|
38
|
-
router.use(rateLimit(deepmerge({
|
|
38
|
+
router.use("/auth", rateLimit(deepmerge({
|
|
39
39
|
windowMs: 5000,
|
|
40
40
|
limit: 10,
|
|
41
41
|
standardHeaders: "draft-7",
|
|
42
42
|
legacyHeaders: false,
|
|
43
|
+
handler: (req, res) => {
|
|
44
|
+
res.status(429).json({
|
|
45
|
+
message: "Too many requests, please try again later",
|
|
46
|
+
});
|
|
47
|
+
},
|
|
43
48
|
}, arkosConfigs?.authentication?.requestRateLimitOptions || {})));
|
|
44
49
|
router.post("/auth/login", handleRequestBodyValidationAndTransformation(getValidationSchemaOrDto("login")), addPrismaQueryOptionsToRequest(prismaQueryOptions, "login"), middlewares?.beforeLogin || authController.login, middlewares?.beforeLogin
|
|
45
50
|
? authController.login
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.router.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,WAAW,MAAM,gBAAgB,CAAC;AACzC,OAAO,SAAS,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EACL,8BAA8B,EAC9B,4CAA4C,EAC5C,YAAY,GACb,MAAM,0BAA0B,CAAC;AAElC,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAG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,cAAc;QAC/B,CAAC,CAAC,WAAW,EAAE,mBAAmB,IAAI,YAAY,EACpD,WAAW,EAAE,oBAAoB,IAAI,WAAW,EAAE,mBAAmB;QACnE,CAAC,CAAC,WAAW,EAAE,mBAAmB;QAClC,CAAC,CAAC,YAAY,EAChB,YAAY,CACb,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { authControllerFactory } from \"./auth.controller\";\nimport authService from \"./auth.service\";\nimport rateLimit from \"express-rate-limit\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../base/base.middlewares\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthPrismaQueryOptions } from \"../../types\";\n\nconst router: Router = Router();\n\nexport async function getAuthRouter(arkosConfigs: ArkosConfig) {\n const { middlewares, dtos, schemas, prismaQueryOptions } =\n await importPrismaModelModules(\"auth\");\n const authController = await authControllerFactory(middlewares);\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (key: string) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n router\n .get(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"getMe\"\n ),\n middlewares?.beforeGetMe || authController.getMe,\n middlewares?.beforeGetMe\n ? authController.getMe\n : middlewares?.afterGetMe || sendResponse,\n middlewares?.beforeGetMe && middlewares?.afterGetMe\n ? middlewares?.afterGetMe\n : sendResponse,\n sendResponse\n )\n .patch(\n \"/users/me\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMe\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updateMe\"\n ),\n middlewares?.beforeUpdateMe || authController.updateMe,\n middlewares?.beforeUpdateMe\n ? authController.updateMe\n : middlewares?.afterUpdateMe || sendResponse,\n middlewares?.beforeUpdateMe && middlewares?.afterUpdateMe\n ? middlewares?.afterUpdateMe\n : sendResponse,\n sendResponse\n )\n .delete(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"deleteMe\"\n ),\n middlewares?.beforeDeleteMe || authController.deleteMe,\n middlewares?.beforeDeleteMe\n ? authController.deleteMe\n : middlewares?.afterDeleteMe || sendResponse,\n middlewares?.beforeDeleteMe && middlewares?.afterDeleteMe\n ? middlewares?.afterDeleteMe\n : sendResponse,\n sendResponse\n );\n\n router.use(\n \"/auth\",\n rateLimit(\n deepmerge(\n {\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (req, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfigs?.authentication?.requestRateLimitOptions || {}\n )\n )\n );\n\n router.post(\n \"/auth/login\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"login\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"login\"\n ),\n middlewares?.beforeLogin || authController.login,\n middlewares?.beforeLogin\n ? authController.login\n : middlewares?.afterLogin || sendResponse,\n middlewares?.beforeLogin && middlewares?.afterLogin\n ? middlewares?.afterLogin\n : sendResponse,\n sendResponse\n );\n\n router.delete(\n \"/auth/logout\",\n authService.authenticate,\n middlewares?.beforeLogout || authController.logout,\n middlewares?.beforeLogout\n ? authController.logout\n : middlewares?.afterLogout || sendResponse,\n middlewares?.beforeLogout && middlewares?.afterLogout\n ? middlewares?.afterLogout\n : sendResponse,\n sendResponse\n );\n\n router.post(\n \"/auth/signup\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"signup\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"signup\"\n ),\n middlewares?.beforeSignup || authController.signup,\n middlewares?.beforeSignup\n ? authController.signup\n : middlewares?.afterSignup || sendResponse,\n middlewares?.beforeSignup && middlewares?.afterSignup\n ? middlewares?.afterSignup\n : sendResponse,\n sendResponse\n );\n\n router.post(\n \"/auth/update-password\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updatePassword\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updatePassword\"\n ),\n middlewares?.beforeUpdatePassword || authController.updatePassword,\n middlewares?.beforeUpdatePassword\n ? authController.updatePassword\n : middlewares?.afterUpdatePassword || sendResponse,\n middlewares?.beforeUpdatePassword && middlewares?.afterUpdatePassword\n ? middlewares?.afterUpdatePassword\n : sendResponse,\n sendResponse\n );\n\n return router;\n}\n"]}
|
|
@@ -90,9 +90,9 @@ export class BaseController {
|
|
|
90
90
|
return next(new AppError("Filter criteria not provided for bulk update.", 400));
|
|
91
91
|
}
|
|
92
92
|
req.query.filterMode = req.query?.filterMode || "AND";
|
|
93
|
-
const
|
|
94
|
-
delete
|
|
95
|
-
const data = await this.service.updateMany(
|
|
93
|
+
const { filters: { where, ...queryOptions }, } = new APIFeatures(req, this.modelName).filter().sort();
|
|
94
|
+
delete queryOptions.include;
|
|
95
|
+
const data = await this.service.updateMany(where, req.body, queryOptions);
|
|
96
96
|
if (!data || data.count === 0) {
|
|
97
97
|
return next(new AppError(`${pluralize(pascalCase(String(this.modelName)))} not found`, 404));
|
|
98
98
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.controller.js","sourceRoot":"","sources":["../../../../src/modules/base/base.controller.ts"],"names":[],"m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AAG,SAAS,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,WAAW,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,CAAC,WAAW,GAAG,eAAe,CAAC,SAAS,CAAC,EAAE,WAAW,IAAI,EAAE,CAAC;IACnE,CAAC;CAuUF;AASD,MAAM,UAAU,iBAAiB,CAC/B,GAAiB,EACjB,GAAkB,EAClB,IAAuB;IAEvB,MAAM,MAAM,GAAG,YAAY,EAAE,CAAC;IAE9B,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnB,CAAC;AASD,MAAM,CAAC,MAAM,qBAAqB,GAAG,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;IACvE,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACnB,IAAI,EAAE,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC;KAClE,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport APIFeatures from \"../../utils/features/api.features\";\nimport { BaseService } from \"./base.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { kebabCase, pascalCase } from \"../../utils/helpers/change-case.helpers\";\nimport { getModelModules, getModels } from \"../../utils/helpers/models.helpers\";\nimport { getAppRoutes } from \"./utils/helpers/base.controller.helpers\";\nimport pluralize from \"pluralize\";\n\n/**\n * BaseController class providing standardized RESTful API endpoints for any prisma model\n * @class BaseController\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-controller-class}\n *\n * **Example:**\n *\n * ```ts\n *\n *\n * ```\n */\nexport class BaseController {\n /**\n * Service instance to handle business logic operations\n * @private\n */\n private service: BaseService;\n\n /**\n * Name of the model this controller handles\n * @private\n */\n private modelName: string;\n\n /**\n * Model-specific middlewares loaded from model modules\n * @private\n */\n private middlewares: any;\n\n /**\n * Creates a new BaseController instance\n * @param {string} modelName - The name of the model for which this controller will handle operations\n */\n constructor(modelName: string) {\n this.modelName = modelName;\n this.service = new BaseService(modelName);\n this.middlewares = getModelModules(modelName)?.middlewares || {};\n }\n\n /**\n * Creates a single resource\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.createOne(\n req.body,\n req.prismaQueryOptions\n );\n\n if (this.middlewares.afterCreateOne) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Creates multiple resources in a single operation\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.createMany(\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n return next(\n new AppError(\n \"Failed to create the resources. Please check your input.\",\n 400\n )\n );\n }\n\n if (this.middlewares.afterCreateMany) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Retrieves multiple resources with filtering, sorting, pagination, and field selection\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const {\n filters: { where, ...queryOptions },\n } = new APIFeatures(\n req,\n this.modelName,\n this.service.relationFields?.singular.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n )\n )\n .filter()\n .sort()\n .limitFields()\n .paginate();\n\n // Execute both operations separately\n const [data, total] = await Promise.all([\n this.service.findMany(where, queryOptions),\n this.service.count(where),\n ]);\n\n if (this.middlewares.afterFindMany) {\n req.responseData = { total, results: data.length, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ total, results: data.length, data });\n }\n );\n\n /**\n * Retrieves a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.findOne(\n req.params,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (\n Object.keys(req.params).length === 1 &&\n \"id\" in req.params &&\n req.params.id !== \"me\"\n ) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterFindOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.updateOne(\n req.params,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterUpdateOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk update.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const features = new APIFeatures(req, this.modelName).filter().sort();\n delete features.filters.include;\n\n const data = await this.service.updateMany(\n features.filters,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data || data.count === 0) {\n return next(\n new AppError(\n `${pluralize(pascalCase(String(this.modelName)))} not found`,\n 404\n )\n );\n }\n\n if (this.middlewares.afterUpdateMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n\n /**\n * Deletes a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.deleteOne(req.params);\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterDeleteOne) {\n req.additionalData = { data };\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).send();\n }\n );\n\n /**\n * Deletes multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk deletion.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const {\n filters: { where },\n } = new APIFeatures(req, this.modelName).filter().sort();\n\n const data = await this.service.deleteMany(where);\n\n if (!data || data.count === 0) {\n return next(new AppError(`No records found to delete`, 404));\n }\n\n if (this.middlewares.afterDeleteMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n}\n\n/**\n * Returns a list of all registered API routes in the Express application\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {void}\n */\nexport function getAvalibleRoutes(\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n) {\n const routes = getAppRoutes();\n\n res.json(routes);\n}\n\n/**\n * Returns a list of all available resource endpoints based on the application's models\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\nexport const getAvailableResources = catchAsync(async (req, res, next) => {\n const models = getModels();\n res.status(200).json({\n data: [...models.map((model) => kebabCase(model)), \"file-upload\"],\n });\n});\n"]}
|
|
1
|
+
{"version":3,"file":"base.controller.js","sourceRoot":"","sources":["../../../../src/modules/base/base.controller.ts"],"names":[],"mappings":"AACA,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,WAAW,MAAM,mCAAmC,CAAC;AAC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,CAAC,CAAC;QAC1C,IAAI,CAAC,WAAW,GAAG,eAAe,CAAC,SAAS,CAAC,EAAE,WAAW,IAAI,EAAE,CAAC;IACnE,CAAC;CAqUF;AASD,MAAM,UAAU,iBAAiB,CAC/B,GAAiB,EACjB,GAAkB,EAClB,IAAuB;IAEvB,MAAM,MAAM,GAAG,YAAY,EAAE,CAAC;IAE9B,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnB,CAAC;AASD,MAAM,CAAC,MAAM,qBAAqB,GAAG,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;IACvE,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACnB,IAAI,EAAE,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC;KAClE,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport APIFeatures from \"../../utils/features/api.features\";\nimport { BaseService } from \"./base.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { kebabCase, pascalCase } from \"../../utils/helpers/change-case.helpers\";\nimport { getModelModules, getModels } from \"../../utils/helpers/models.helpers\";\nimport { getAppRoutes } from \"./utils/helpers/base.controller.helpers\";\nimport pluralize from \"pluralize\";\n\n/**\n * BaseController class providing standardized RESTful API endpoints for any prisma model\n * @class BaseController\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-controller-class}\n *\n * **Example:**\n *\n * ```ts\n *\n *\n * ```\n */\nexport class BaseController {\n /**\n * Service instance to handle business logic operations\n * @private\n */\n private service: BaseService;\n\n /**\n * Name of the model this controller handles\n * @private\n */\n private modelName: string;\n\n /**\n * Model-specific middlewares loaded from model modules\n * @private\n */\n private middlewares: any;\n\n /**\n * Creates a new BaseController instance\n * @param {string} modelName - The name of the model for which this controller will handle operations\n */\n constructor(modelName: string) {\n this.modelName = modelName;\n this.service = new BaseService(modelName);\n this.middlewares = getModelModules(modelName)?.middlewares || {};\n }\n\n /**\n * Creates a single resource\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.createOne(\n req.body,\n req.prismaQueryOptions\n );\n\n if (this.middlewares.afterCreateOne) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Creates multiple resources in a single operation\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n createMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.createMany(\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n return next(\n new AppError(\n \"Failed to create the resources. Please check your input.\",\n 400\n )\n );\n }\n\n if (this.middlewares.afterCreateMany) {\n req.responseData = { data };\n req.responseStatus = 201;\n return next();\n }\n\n res.status(201).json({ data });\n }\n );\n\n /**\n * Retrieves multiple resources with filtering, sorting, pagination, and field selection\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const {\n filters: { where, ...queryOptions },\n } = new APIFeatures(\n req,\n this.modelName,\n this.service.relationFields?.singular.reduce(\n (acc: Record<string, boolean>, curr) => {\n acc[curr.name] = true;\n return acc;\n },\n {}\n )\n )\n .filter()\n .sort()\n .limitFields()\n .paginate();\n\n // Execute both operations separately\n const [data, total] = await Promise.all([\n this.service.findMany(where, queryOptions),\n this.service.count(where),\n ]);\n\n if (this.middlewares.afterFindMany) {\n req.responseData = { total, results: data.length, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ total, results: data.length, data });\n }\n );\n\n /**\n * Retrieves a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n findOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.findOne(\n req.params,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (\n Object.keys(req.params).length === 1 &&\n \"id\" in req.params &&\n req.params.id !== \"me\"\n ) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterFindOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.updateOne(\n req.params,\n req.body,\n req.prismaQueryOptions\n );\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterUpdateOne) {\n req.responseData = { data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data });\n }\n );\n\n /**\n * Updates multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n updateMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk update.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const {\n filters: { where, ...queryOptions },\n } = new APIFeatures(req, this.modelName).filter().sort();\n delete queryOptions.include;\n\n const data = await this.service.updateMany(where, req.body, queryOptions);\n\n if (!data || data.count === 0) {\n return next(\n new AppError(\n `${pluralize(pascalCase(String(this.modelName)))} not found`,\n 404\n )\n );\n }\n\n if (this.middlewares.afterUpdateMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n\n /**\n * Deletes a single resource by its identifier\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteOne = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const data = await this.service.deleteOne(req.params);\n\n if (!data) {\n if (Object.keys(req.params).length === 1 && \"id\" in req.params) {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} with ID ${\n req.params?.id\n } not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n } else {\n return next(\n new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"not_found\"\n )\n );\n }\n }\n\n if (this.middlewares.afterDeleteOne) {\n req.additionalData = { data };\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).send();\n }\n );\n\n /**\n * Deletes multiple resources that match specified criteria\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\n deleteMany = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n if (!Object.keys(req.query).some((key) => key !== \"prismaQueryOptions\")) {\n return next(\n new AppError(\"Filter criteria not provided for bulk deletion.\", 400)\n );\n }\n\n req.query.filterMode = req.query?.filterMode || \"AND\";\n const {\n filters: { where },\n } = new APIFeatures(req, this.modelName).filter().sort();\n\n const data = await this.service.deleteMany(where);\n\n if (!data || data.count === 0) {\n return next(new AppError(`No records found to delete`, 404));\n }\n\n if (this.middlewares.afterDeleteMany) {\n req.responseData = { results: data.count, data };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ results: data.count, data });\n }\n );\n}\n\n/**\n * Returns a list of all registered API routes in the Express application\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {void}\n */\nexport function getAvalibleRoutes(\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n) {\n const routes = getAppRoutes();\n\n res.json(routes);\n}\n\n/**\n * Returns a list of all available resource endpoints based on the application's models\n * @param {ArkosRequest} req - Express request object\n * @param {ArkosResponse} res - Express response object\n * @param {ArkosNextFunction} next - Express next function\n * @returns {Promise<void>}\n */\nexport const getAvailableResources = catchAsync(async (req, res, next) => {\n const models = getModels();\n res.status(200).json({\n data: [...models.map((model) => kebabCase(model)), \"file-upload\"],\n });\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.service.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,oBAAoB,GACrB,MAAM,0CAA0C,CAAC;AAQlD,MAAM,UAAU,eAAe,CAAC,GAAwB;IAC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,CAAC,SAAS;QAAE,OAAO,KAAK,CAAC;IAG7B,IAAI,SAAS,CAAC,SAAS,IAAI,CAAC,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC;QACzE,OAAO,KAAK,CAAC;IACf,CAAC;IAGD,IAAI,SAAS,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAGD,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,KAAK,CAAC,IAAI,SAAS,EAAE,EAAE,EAAE,CAAC;QAC1D,OAAO,IAAI,CAAC;IACd,CAAC;IAGD,MAAM,YAAY,GAAG,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAGrD,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxC,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5C,OAAO,YAAY,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IACjE,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n getPrismaModelRelations,\n RelationFields,\n getModelUniqueFields,\n} from \"../../../../utils/helpers/models.helpers\";\n\n/**\n * Removes apiAction field from an object and all nested objects\n *\n * @param {Record<string, any>} obj - The object to clean\n * @returns {Record<string, any>} - The cleaned object\n */\nexport function removeApiAction(obj: Record<string, any>): Record<string, any> {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const result: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (key === \"apiAction\") continue;\n\n if (Array.isArray(value)) {\n result[key] = value.map((item) =>\n typeof item === \"object\" && item !== null ? removeApiAction(item) : item\n );\n } else if (typeof value === \"object\" && value !== null) {\n result[key] = removeApiAction(value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Checks if an object is already formatted as a Prisma relation operation\n *\n * @param {Record<string, any>} obj - The object to check\n * @returns {boolean} - True if the object contains Prisma relation operations\n */\nexport function isPrismaRelationFormat(obj: Record<string, any>): boolean {\n if (!obj || typeof obj !== \"object\") return false;\n\n // Common Prisma relation operations\n const prismaOperations = [\n \"create\",\n \"connect\",\n \"update\",\n \"delete\",\n \"disconnect\",\n \"deleteMany\",\n \"connectOrCreate\",\n \"upsert\",\n \"set\",\n ];\n\n // Check if any key is a Prisma operation\n return prismaOperations.some((op) => op in obj);\n}\n\n/**\n * Determines the appropriate Prisma operation (`create`, `connect`, `update`, `delete`, or `disconnect`)\n * for each relation field in the provided body based on its nested data and recursively does the same for each relation field.\n *\n * This function handles the following types of relations:\n * - **One-to-one**\n * - **One-to-many**\n *\n *\n * ### Operation Rules:\n *\n *\n * - **Create**: Used when the nested relation data is provided **without an `id` or unique field**.\n * - **Connect**: Used when the nested relation data contains **only an `id` or a unique field** (e.g., email).\n * - **Update**: Used when the nested relation data contains **both an `id` and additional fields**.\n * - **Delete**: Used when the nested relation data includes **`apiAction: \"delete\"`**.\n * - **Disconnect**: Used when the nested relation data includes **`apiAction: \"disconnect\"`**.\n *\n * The function will preserve existing Prisma operation formats if detected,\n * allowing developers to manually structure relation operations when needed.\n *\n * @param {Record<string, any>} body - The object containing relation fields to be processed.\n * @param {Object} relationFields - Defines relation field types.\n * @param {RelationFields[]} relationFields.singular - List of one-side relation field names (one-to-one).\n * @param {RelationFields[]} relationFields.list - List of many-side relation field names (one-to-many).\n * @param {string[]} ignoreActions - Optional list of apiAction values to ignore.\n * @returns {Record<string, any>} The transformed data with appropriate Prisma operations applied.\n */\nexport function handleRelationFieldsInBody(\n body: Record<string, any>,\n relationFields: RelationFields,\n ignoreActions: string[] = []\n) {\n let mutableBody = { ...body };\n\n relationFields?.list?.forEach((field) => {\n if (!body[field.name]) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n // Skip if the field is not an array (likely already handled manually)\n if (!Array.isArray(body[field.name])) {\n return;\n }\n\n const createData: any[] = [];\n const connectData: any[] = [];\n const updateData: any[] = [];\n const disconnectData: any[] = [];\n const deleteManyIds: any[] = [];\n\n body[field.name]?.forEach((bodyField: any) => {\n if (ignoreActions?.includes?.(bodyField?.apiAction)) return;\n\n const apiAction = bodyField?.apiAction;\n\n if (apiAction === \"delete\") {\n deleteManyIds.push(bodyField.id);\n } else if (apiAction === \"disconnect\") {\n disconnectData.push({ id: bodyField.id });\n } else if (canBeUsedToConnect(field.type, bodyField)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = bodyField;\n connectData.push(cleanedData);\n } else if (!bodyField?.id) {\n // If no ID, assume create operation\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = { ...bodyField };\n\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n dataToPush,\n nestedRelations,\n ignoreActions\n );\n }\n\n // Ensure apiAction is removed\n if (\"apiAction\" in dataToPush) {\n const { apiAction: _, ...rest } = dataToPush;\n dataToPush = rest;\n }\n\n createData.push(dataToPush);\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = bodyField;\n\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = data;\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n updateData.push({\n where: { id },\n data: dataToPush,\n });\n }\n });\n\n mutableBody[field.name] = {\n ...(createData.length ? { create: createData } : {}),\n ...(connectData.length ? { connect: connectData } : {}),\n ...(updateData.length ? { update: updateData } : {}),\n ...(disconnectData.length ? { disconnect: disconnectData } : {}),\n ...(deleteManyIds.length\n ? { deleteMany: { id: { in: deleteManyIds } } }\n : {}),\n };\n });\n\n relationFields?.singular?.forEach((field) => {\n if (!body[field.name]) return;\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n const relationData = body[field.name];\n let nestedRelations = getPrismaModelRelations(field.type);\n\n if (canBeUsedToConnect(field.type, relationData)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = relationData;\n mutableBody[field.name] = { connect: cleanedData };\n } else if (!relationData?.id) {\n // If no ID, assume create operation\n let dataToCreate = { ...relationData };\n\n if (\"apiAction\" in dataToCreate) {\n const { apiAction: _, ...rest } = dataToCreate;\n dataToCreate = rest;\n }\n\n if (nestedRelations) {\n dataToCreate = handleRelationFieldsInBody(\n dataToCreate,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = { create: dataToCreate };\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = relationData;\n\n let dataToUpdate = data;\n if (nestedRelations) {\n dataToUpdate = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = {\n update: {\n data: dataToUpdate,\n },\n };\n }\n });\n\n // Remove any remaining apiAction fields from the top level\n if (\"apiAction\" in mutableBody) {\n const { apiAction, ...rest } = mutableBody;\n mutableBody = rest;\n }\n\n // As a final step, recursively remove any remaining apiAction fields\n return removeApiAction(mutableBody);\n}\n\n/**\n * Checks if a field value can be used to connect to a model\n * This happens when the field contains only an ID or a single unique field\n *\n * @param {string} modelName - The model name to get unique fields for\n * @param {Record<string, any>} bodyField - The field value from the body\n * @returns {boolean} True if the field can be used for a connect operation\n */\nexport function canBeUsedToConnect(\n modelName: string,\n bodyField: Record<string, any> | undefined | null\n): boolean {\n // If the field is null or undefined, it can't be used to connect\n if (!bodyField) return false;\n\n // If the field has an apiAction that's not for connecting, return false\n if (bodyField.apiAction && ![\"connect\"]?.includes?.(bodyField.apiAction)) {\n return false;\n }\n\n // If explicitly marked for connect, allow it\n if (bodyField.apiAction === \"connect\") {\n return true;\n }\n\n // If only ID is present, it can be used to connect\n if (Object.keys(bodyField)?.length === 1 && bodyField?.id) {\n return true;\n }\n\n // Get unique fields for the model\n const uniqueFields = getModelUniqueFields(modelName);\n\n // If the field has exactly one property and it's a unique field, it can be used to connect\n if (Object.keys(bodyField).length === 1) {\n const fieldName = Object.keys(bodyField)[0];\n return uniqueFields?.some((field) => field.name === fieldName);\n }\n\n return false;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.service.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,oBAAoB,GACrB,MAAM,0CAA0C,CAAC;AAQlD,MAAM,UAAU,eAAe,CAAC,GAAwB;IACtD,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC;IAEhD,MAAM,MAAM,GAAwB,EAAE,CAAC;IAEvC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,IAAI,GAAG,KAAK,WAAW;YAAE,SAAS;QAElC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAC/B,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CACzE,CAAC;QACJ,CAAC;aAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACvD,MAAM,CAAC,GAAG,CAAC,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QACvC,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACtB,CA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AC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n getPrismaModelRelations,\n RelationFields,\n getModelUniqueFields,\n} from \"../../../../utils/helpers/models.helpers\";\n\n/**\n * Removes apiAction field from an object and all nested objects\n *\n * @param {Record<string, any>} obj - The object to clean\n * @returns {Record<string, any>} - The cleaned object\n */\nexport function removeApiAction(obj: Record<string, any>): Record<string, any> {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const result: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (key === \"apiAction\") continue;\n\n if (Array.isArray(value)) {\n result[key] = value.map((item) =>\n typeof item === \"object\" && item !== null ? removeApiAction(item) : item\n );\n } else if (typeof value === \"object\" && value !== null) {\n result[key] = removeApiAction(value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Checks if an object is already formatted as a Prisma relation operation\n *\n * @param {Record<string, any>} obj - The object to check\n * @returns {boolean} - True if the object contains Prisma relation operations\n */\nexport function isPrismaRelationFormat(obj: Record<string, any>): boolean {\n if (!obj || typeof obj !== \"object\") return false;\n\n // Common Prisma relation operations\n const prismaOperations = [\n \"create\",\n \"connect\",\n \"update\",\n \"delete\",\n \"disconnect\",\n \"deleteMany\",\n \"connectOrCreate\",\n \"upsert\",\n \"set\",\n ];\n\n // Check if any key is a Prisma operation\n return prismaOperations.some((op) => op in obj);\n}\n\n/**\n * Determines the appropriate Prisma operation (`create`, `connect`, `update`, `delete`, or `disconnect`)\n * for each relation field in the provided body based on its nested data and recursively does the same for each relation field.\n *\n * This function handles the following types of relations:\n * - **One-to-one**\n * - **One-to-many**\n *\n *\n * ### Operation Rules:\n *\n *\n * - **Create**: Used when the nested relation data is provided **without an `id` or unique field**.\n * - **Connect**: Used when the nested relation data contains **only an `id` or a unique field** (e.g., email).\n * - **Update**: Used when the nested relation data contains **both an `id` and additional fields**.\n * - **Delete**: Used when the nested relation data includes **`apiAction: \"delete\"`**.\n * - **Disconnect**: Used when the nested relation data includes **`apiAction: \"disconnect\"`**.\n *\n * The function will preserve existing Prisma operation formats if detected,\n * allowing developers to manually structure relation operations when needed.\n *\n * @param {Record<string, any>} body - The object containing relation fields to be processed.\n * @param {Object} relationFields - Defines relation field types.\n * @param {RelationFields[]} relationFields.singular - List of one-side relation field names (one-to-one).\n * @param {RelationFields[]} relationFields.list - List of many-side relation field names (one-to-many).\n * @param {string[]} ignoreActions - Optional list of apiAction values to ignore.\n * @returns {Record<string, any>} The transformed data with appropriate Prisma operations applied.\n */\nexport function handleRelationFieldsInBody(\n body: Record<string, any>,\n relationFields: RelationFields,\n ignoreActions: string[] = []\n) {\n let mutableBody = { ...body };\n\n relationFields?.list?.forEach((field) => {\n if (!body[field.name]) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n // Skip if the field is not an array (likely already handled manually)\n if (!Array.isArray(body[field.name])) {\n return;\n }\n\n const createData: any[] = [];\n const connectData: any[] = [];\n const updateData: any[] = [];\n const disconnectData: any[] = [];\n const deleteManyIds: any[] = [];\n\n body[field.name]?.forEach((bodyField: any) => {\n if (ignoreActions?.includes?.(bodyField?.apiAction)) return;\n\n const apiAction = bodyField?.apiAction;\n\n if (apiAction === \"delete\") {\n deleteManyIds.push(bodyField.id);\n } else if (apiAction === \"disconnect\") {\n disconnectData.push({ id: bodyField.id });\n } else if (canBeUsedToConnect(field.type, bodyField)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = bodyField;\n connectData.push(cleanedData);\n } else if (!bodyField?.id) {\n // If no ID, assume create operation\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = { ...bodyField };\n\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n dataToPush,\n nestedRelations,\n ignoreActions\n );\n }\n\n // Ensure apiAction is removed\n if (\"apiAction\" in dataToPush) {\n const { apiAction: _, ...rest } = dataToPush;\n dataToPush = rest;\n }\n\n createData.push(dataToPush);\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = bodyField;\n\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = data;\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n updateData.push({\n where: { id },\n data: dataToPush,\n });\n }\n });\n\n mutableBody[field.name] = {\n ...(createData.length ? { create: createData } : {}),\n ...(connectData.length ? { connect: connectData } : {}),\n ...(updateData.length ? { update: updateData } : {}),\n ...(disconnectData.length ? { disconnect: disconnectData } : {}),\n ...(deleteManyIds.length\n ? { deleteMany: { id: { in: deleteManyIds } } }\n : {}),\n };\n });\n\n relationFields?.singular?.forEach((field) => {\n if (!body[field.name]) return;\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n const relationData = body[field.name];\n let nestedRelations = getPrismaModelRelations(field.type);\n\n if (canBeUsedToConnect(field.type, relationData)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = relationData;\n mutableBody[field.name] = { connect: cleanedData };\n } else if (!relationData?.id) {\n // If no ID, assume create operation\n let dataToCreate = { ...relationData };\n\n if (\"apiAction\" in dataToCreate) {\n const { apiAction: _, ...rest } = dataToCreate;\n dataToCreate = rest;\n }\n\n if (nestedRelations) {\n dataToCreate = handleRelationFieldsInBody(\n dataToCreate,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = { create: dataToCreate };\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = relationData;\n\n let dataToUpdate = data;\n if (nestedRelations) {\n dataToUpdate = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = {\n update: {\n data: dataToUpdate,\n },\n };\n }\n });\n\n // Remove any remaining apiAction fields from the top level\n if (\"apiAction\" in mutableBody) {\n const { apiAction, ...rest } = mutableBody;\n mutableBody = rest;\n }\n\n // As a final step, recursively remove any remaining apiAction fields\n return removeApiAction(mutableBody);\n}\n\n/**\n * Checks if a field value can be used to connect to a model\n * This happens when the field contains only an ID or a single unique field\n *\n * @param {string} modelName - The model name to get unique fields for\n * @param {Record<string, any>} bodyField - The field value from the body\n * @returns {boolean} True if the field can be used for a connect operation\n */\nexport function canBeUsedToConnect(\n modelName: string,\n bodyField: Record<string, any> | undefined | null\n): boolean {\n // If the field is null or undefined, it can't be used to connect\n if (!bodyField) return false;\n\n // If the field has an apiAction that's not for connecting, return false\n if (bodyField.apiAction && ![\"connect\"]?.includes?.(bodyField.apiAction)) {\n return false;\n }\n\n // If explicitly marked for connect, allow it\n if (bodyField.apiAction === \"connect\") {\n return true;\n }\n\n // If only ID is present, it can be used to connect\n if (Object.keys(bodyField)?.length === 1 && bodyField?.id) {\n return true;\n }\n\n // Get unique fields for the model\n const uniqueFields = getModelUniqueFields(modelName);\n\n // If the field has exactly one property and it's a unique field, it can be used to connect\n if (Object.keys(bodyField).length === 1) {\n const fieldName = Object.keys(bodyField)[0];\n return uniqueFields?.some((field) => field.name === fieldName);\n }\n\n return false;\n}\n\n// /**\n// * Checks if a list field is actually an array\n// *\n// * @param {any} field - The field to check\n// * @returns {boolean} - True if the field is an array\n// */\n// export function isListFieldAnArray(field: any): boolean {\n// return Array.isArray(field);\n// }\n"]}
|
|
@@ -44,7 +44,7 @@ export default function errorHandler(err, req, res, next) {
|
|
|
44
44
|
error = errorControllerHelper.handleVersionMismatchError(err);
|
|
45
45
|
if (err.name === "NetworkError")
|
|
46
46
|
error = errorControllerHelper.handleNetworkError(err);
|
|
47
|
-
if (!
|
|
47
|
+
if (!error.isOperational)
|
|
48
48
|
error = new AppError("Something went wrong!", 500);
|
|
49
49
|
sendProductionError(error, req, res);
|
|
50
50
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"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AAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACnB,MAAM,EAAE,OAAO;gBACf,OAAO,EAAE,uBAAuB;aACjC,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;SACrB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,yBAAyB;KACnC,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n next: NextFunction\n): void {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"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 // Handle general error types (e.g., syntax errors, type errors, etc.)\n // if (err.name === \"SyntaxError\")\n // error = errorControllerHelper.handleSchemaSyntaxError(err);\n // if (err.name === \"TypeError\")\n // error = errorControllerHelper.handleClientTypeError(err);\n // if (err.name === \"BinaryError\")\n // error = errorControllerHelper.handleBinaryError(err);\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n // if (err.name === \"UnhandledPromiseRejection\")\n // error = errorControllerHelper.handleUnhandledPromiseError(err);\n if (!err.isOperational) error = new AppError(\"Something went wrong!\", 500);\n\n // Send the error response for production environment\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n });\n }\n});\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AACzC,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiBtC,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,IAAkB;IAElB,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAGnC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC1C,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;QACpC,OAAO;IACT,CAAC;IAGD,IAAI,KAAK,GAAG,EAAE,GAAG,GAAG,EAAE,OAAO,EAAE,G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,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n next: NextFunction\n): void {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"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 // Handle general error types (e.g., syntax errors, type errors, etc.)\n // if (err.name === \"SyntaxError\")\n // error = errorControllerHelper.handleSchemaSyntaxError(err);\n // if (err.name === \"TypeError\")\n // error = errorControllerHelper.handleClientTypeError(err);\n // if (err.name === \"BinaryError\")\n // error = errorControllerHelper.handleBinaryError(err);\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n // if (err.name === \"UnhandledPromiseRejection\")\n // error = errorControllerHelper.handleUnhandledPromiseError(err);\n if (!error.isOperational) error = new AppError(\"Something went wrong!\", 500);\n\n // Send the error response for production environment\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n });\n }\n});\n"]}
|