arkos 1.1.58-test → 1.1.60-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/modules/auth/auth.controller.js.map +1 -1
- package/dist/cjs/modules/base/base.controller.js +12 -13
- package/dist/cjs/modules/base/base.controller.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +6 -4
- package/dist/cjs/modules/base/utils/helpers/base.router.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 +2 -0
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -0
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/types/arkos-config.js.map +1 -1
- package/dist/cjs/types/router-config.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +5 -2
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/es2020/modules/auth/auth.controller.js.map +1 -1
- package/dist/es2020/modules/base/base.controller.js +12 -13
- package/dist/es2020/modules/base/base.controller.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js +6 -4
- package/dist/es2020/modules/base/utils/helpers/base.router.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 +2 -0
- package/dist/es2020/modules/swagger/swagger.router.js.map +1 -0
- package/dist/es2020/server.js.map +1 -1
- package/dist/es2020/types/arkos-config.js.map +1 -1
- package/dist/es2020/types/router-config.js.map +1 -1
- package/dist/es2020/utils/helpers/models.helpers.js +5 -2
- package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
- package/dist/types/modules/base/base.controller.d.ts +1 -1
- package/dist/types/modules/swagger/swagger.router.d.ts +0 -0
- package/dist/types/types/router-config.d.ts +2 -2
- package/dist/types/utils/helpers/models.helpers.d.ts +1 -1
- package/package.json +1 -1
|
@@ -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 allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-http-server#calling-serverlisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
|
|
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 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":"router-config.js","sourceRoot":"","sources":["../../../src/types/router-config.ts"],"names":[],"mappings":"","sourcesContent":["export type RouterEndpoint =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"updateMany\"\n | \"deleteMany\";\n\n/**\n * Allows to customize the generated routers\n *\n * See docs [https://www.arkosjs.com/docs/
|
|
1
|
+
{"version":3,"file":"router-config.js","sourceRoot":"","sources":["../../../src/types/router-config.ts"],"names":[],"mappings":"","sourcesContent":["export type RouterEndpoint =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"updateMany\"\n | \"deleteMany\";\n\n/**\n * Allows to customize the generated routers\n *\n * See docs [https://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers](https://https://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers)\n */\nexport type RouterConfig = {\n /**\n * Allows to configure nested routes.\n *\n * **Example**\n *\n * ```curl\n * GET /api/authors/:id/posts\n * ```\n *\n * Returning only the fields belonging to the passed author id.\n *\n * See more at [ttps://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers](https://ttps://www.arkosjs.com/docs/guide/adding-custom-routers#2-customizing-prisma-model-routers)\n */\n parent?: {\n /**\n * Your prisma model name in kebab-case and singular.\n */\n model?: string;\n /**\n * Defines the parentId field stores the Id relation. e.g authorId, categoryId, productId.\n *\n *\n *\n * **Note**: By default **Arkos** will look for modelNameId, modelName being the model specified in `parent.model`.\n *\n * **Example**\n * ```prisma\n * model Post {\n * // other fields\n * authorId String\n * author Author @relation(fields: [authorId], references: [id])\n * }\n * ```\n *\n * When passed `parent.model` to `author` **Arkos** will create an endpoint:\n * ```curl\n * GET /api/authors/:id/posts\n * GET /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts\n * UPDATE /api/authors/:id/posts/:id\n * DELETE /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts/many\n * UPDATE /api/authors/:id/posts/many\n * DELETE /api/authors/:id/posts/many\n * ```\n *\n * If you want to point to a different field pass it here.\n */\n foreignKeyField?: string;\n /**\n * Customizes what endpoints to be created.\n *\n * Default is \"*\" to generate all endpoints\n */\n endpoints?: \"*\" | RouterEndpoint[];\n };\n /**\n * Use to disable endpoints or the whole router\n *\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * GET /api/[mode-name]/:id\n * PATCH /api/[mode-name]:id\n * DELETE /api/[mode-name]:id\n * POST /api/[mode-name]/many\n * GET /api/[mode-name]\n * UPDATE /api/[mode-name]/many\n * DELETE /api/[mode-name]/many\n * ```\n */\n disable?:\n | boolean\n | {\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * ```\n */\n createOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]/:id\n * ```\n */\n findOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * PATCH /api/[mode-name]:id\n * ```\n */\n updateOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]:id\n * ```\n */\n deleteOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]/many\n * ```\n */\n createMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]\n * ```\n */\n findMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * UPDATE /api/[mode-name]/many\n * ```\n */\n updateMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]/many\n * ```\n */\n deleteMany?: boolean;\n };\n};\n"]}
|
|
@@ -129,10 +129,12 @@ async function processSubdir(modelName, type, result) {
|
|
|
129
129
|
}
|
|
130
130
|
}
|
|
131
131
|
catch (error) {
|
|
132
|
+
console.error(error);
|
|
132
133
|
}
|
|
133
134
|
}));
|
|
134
135
|
}
|
|
135
136
|
catch (error) {
|
|
137
|
+
console.error(error);
|
|
136
138
|
}
|
|
137
139
|
}
|
|
138
140
|
async function importPrismaModelModules(modelName) {
|
|
@@ -184,7 +186,7 @@ function getAllPrismaFiles(dirPath, fileList = []) {
|
|
|
184
186
|
const modelRegex = /model\s+(\w+)\s*{/g;
|
|
185
187
|
exports.models = [];
|
|
186
188
|
exports.prismaModelsUniqueFields = [];
|
|
187
|
-
function initializePrismaModels(
|
|
189
|
+
function initializePrismaModels() {
|
|
188
190
|
const prismaContent = [];
|
|
189
191
|
const files = getAllPrismaFiles("./prisma");
|
|
190
192
|
for (const file of files) {
|
|
@@ -213,7 +215,8 @@ function initializePrismaModels(testName) {
|
|
|
213
215
|
const trimmedLine = line.trim();
|
|
214
216
|
if (!trimmedLine ||
|
|
215
217
|
trimmedLine.startsWith("model") ||
|
|
216
|
-
trimmedLine.startsWith("//")
|
|
218
|
+
trimmedLine.startsWith("//") ||
|
|
219
|
+
trimmedLine.startsWith("/*"))
|
|
217
220
|
continue;
|
|
218
221
|
const [fieldName, type] = trimmedLine.split(/\s+/);
|
|
219
222
|
const isUnique = trimmedLine?.includes?.("@unique");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,0CAEC;AAED,4EA6CC;AAED,sCAmDC;AAoBD,4DAyCC;AA2BD,8CAgBC;AAOD,wDA4G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O,gCAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n // console.log(`-------${modelName}--------------`);\n // console.log(key, moduleDir, filePath);\n // console.log(JSON.stringify(module, null, 2));\n // console.log(`-------${modelName}--------------\\n`);\n if (module) {\n if (key === \"middlewares\") result[key] = module;\n else if (key === \"router\") result[key] = module;\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch (err) {\n console.error(err);\n }\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels(testName?: string) {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine?.includes?.(\"@unique\");\n\n if (isUnique) {\n const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\n }\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine?.includes?.(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models?.includes?.(camelCase(cleanType || \"\"))\n ) {\n const enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n\n // && !content.includes?.(`model ${cleanType} {`)\n ) {\n continue;\n }\n\n if (!type?.includes?.(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n }\n}\n\ninitializePrismaModels();\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
1
|
+
{"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,0CAEC;AAED,4EA6CC;AAED,sCAqDC;AAoBD,4DAsCC;AA2BD,8CAgBC;AAOD,wDA6GC;AAUD,0DAKC;AAmBQ,8BAAS;AAAE,oDAAoB;AAnXxC,gDAAw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AM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,gCAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\nimport {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\nimport { AuthConfigs } from \"../../types/auth\";\n\nexport let prismaModelsModules: Record<\n string,\n Awaited<ReturnType<typeof importPrismaModelModules>>\n> = {};\n\nexport function getModelModules(modelName: string) {\n return prismaModelsModules[kebabCase(modelName)];\n}\n\nexport function getFileModelModulesFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n service: `${kebabModelName}.service.${ext}`,\n controller: `${kebabModelName}.controller.${ext}`,\n middlewares: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth-configs.${ext}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createMany: `create-many-${kebabModelName}.dto.${ext}`,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateMany: `update-many-${kebabModelName}.dto.${ext}`,\n query: `query-${kebabModelName}.dto.${ext}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createMany: `create-many-${kebabModelName}.schema.${ext}`,\n update: `update-${kebabModelName}.schema.${ext}`,\n updateMany: `update-many-${kebabModelName}.schema.${ext}`,\n query: `query-${kebabModelName}.schema.${ext}`,\n },\n };\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\",\n result: Record<string, any>\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const pascalModelName = pascalCase(modelName);\n const fileStructure = getFileModelModulesFileStructure(modelName);\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Skip if directory doesn't exist\n try {\n await fs.promises.access(subdir).catch(() => {\n return; // Directory doesn't exist\n });\n\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n try {\n const module = await import(filePath).catch(() => null);\n if (module) {\n if (isAuthModule) {\n // Auth module uses different naming conventions\n const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);\n const expectedName = `${pascalKey}${\n type === \"dtos\" ? \"Dto\" : \"Schema\"\n }`;\n result[type][key] = module.default;\n } else {\n // Standard modules\n const expectedName =\n key === \"model\"\n ? `${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`\n : `${\n key.charAt(0).toUpperCase() + key.slice(1)\n }${pascalModelName}${type === \"dtos\" ? \"Dto\" : \"Schema\"}`;\n\n result[type][key] = module.default;\n }\n }\n } catch (error) {\n // Silent fail - file might not exist\n console.error(error);\n }\n })\n );\n } catch (error) {\n // Directory doesn't exist, continue silently\n console.error(error);\n }\n}\n\ntype importPrismaModelModulesReturnType = {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: AuthConfigs;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n};\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importPrismaModelModules(\n modelName: string\n): Promise<importPrismaModelModulesReturnType> {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const result: importPrismaModelModulesReturnType = {\n dtos: {},\n schemas: {},\n };\n\n const fileStructure = getFileModelModulesFileStructure(modelName);\n // Batch process core files\n await Promise.all(\n Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n const filePath = path.join(moduleDir, fileName);\n try {\n const module = await importModule(filePath).catch(() => null);\n\n if (module) {\n if (key === \"middlewares\") result[key] = module;\n else if (key === \"router\") result[key] = module;\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch (err) {\n console.error(err);\n }\n })\n );\n\n await Promise.all([\n processSubdir(modelName, \"dtos\", result),\n processSubdir(modelName, \"schemas\", result),\n ]);\n\n // Cache the result\n prismaModelsModules[modelName] = result;\n\n return result;\n}\n\nexport type ModelFieldDefition = {\n name: string;\n type: string;\n isUnique: boolean;\n};\n\n/**\n * Represents the structure of relation fields for Prisma models.\n * It includes both singular (one-to-one) and list (one-to-many) relationships.\n *\n * @typedef {Object} RelationFields\n * @property {Array<{name: string, type: string}>} singular - List of singular relationships.\n * @property {Array<{name: string, type: string}>} list - List of list relationships.\n */\nexport type RelationFields = {\n singular: Omit<ModelFieldDefition, \"isUnique\">[];\n list: Omit<ModelFieldDefition, \"isUnique\">[];\n};\n\n/**\n * Reads the Prisma schema files and extracts all model definitions,\n * identifying their relations (one-to-one and one-to-many).\n */\nexport const prismaModelRelationFields: Record<string, RelationFields> = {};\n\nexport function getAllPrismaFiles(dirPath: string, fileList: string[] = []) {\n const files = fs.readdirSync(dirPath);\n\n files?.forEach((file) => {\n const filePath = path.join(dirPath, file);\n const stat = fs.statSync(filePath);\n\n // Skip migrations folder\n if (stat.isDirectory() && file !== \"migrations\") {\n fileList = getAllPrismaFiles(filePath, fileList);\n } else if (stat.isFile() && file.endsWith(\".prisma\")) {\n fileList.push(filePath);\n }\n });\n\n return fileList;\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nexport const models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nexport function initializePrismaModels() {\n const prismaContent: string[] = [];\n\n const files = getAllPrismaFiles(\"./prisma\");\n\n for (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n if (!prismaContent?.includes?.(content)) prismaContent.push(content);\n }\n\n const content = prismaContent\n .join(\"\\n\")\n .replace(modelRegex, (_, modelName) => {\n if (!models?.includes?.(modelName))\n models.push(camelCase(modelName.trim()));\n return `model ${modelName} {`;\n });\n\n for (const model of models) {\n const modelName = pascalCase(model);\n\n const modelStart = content.indexOf(`model ${modelName} {`);\n const modelEnd = content.indexOf(\"}\", modelStart);\n const modelDefinition = content.slice(modelStart, modelEnd);\n\n const relations: RelationFields = {\n singular: [],\n list: [],\n };\n const lines = modelDefinition.split(\"\\n\");\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (\n !trimmedLine ||\n trimmedLine.startsWith(\"model\") ||\n trimmedLine.startsWith(\"//\") ||\n trimmedLine.startsWith(\"/*\")\n )\n continue;\n\n const [fieldName, type] = trimmedLine.split(/\\s+/);\n const isUnique = trimmedLine?.includes?.(\"@unique\");\n\n if (isUnique) {\n const existingFields = prismaModelsUniqueFields[model] || [];\n\n const alreadyExists = existingFields.some(\n (field) =>\n field.name === fieldName &&\n field.type === type &&\n field.isUnique === isUnique\n );\n\n if (!alreadyExists) {\n prismaModelsUniqueFields[model] = [\n ...existingFields,\n { name: fieldName, type, isUnique },\n ];\n }\n }\n\n const cleanType = type?.replace(\"[]\", \"\").replace(\"?\", \"\");\n\n if (\n trimmedLine?.includes?.(\"@relation\") ||\n trimmedLine.match(/\\s+\\w+(\\[\\])?(\\s+@|$)/) ||\n models?.includes?.(camelCase(cleanType || \"\"))\n ) {\n const enumStart = content.indexOf(`enum ${cleanType} {`);\n const typeStart = content.indexOf(`type ${cleanType} {`);\n\n if (\n !cleanType ||\n enumStart >= 0 ||\n typeStart >= 0 ||\n cleanType === \"String\" ||\n cleanType === \"Int\" ||\n cleanType === \"Float\" ||\n cleanType === \"Boolean\" ||\n cleanType === \"DateTime\" ||\n cleanType === \"Bytes\" ||\n cleanType === \"Decimal\" ||\n cleanType === \"BigInt\" ||\n cleanType === \"Json\"\n\n // && !content.includes?.(`model ${cleanType} {`)\n ) {\n continue;\n }\n\n if (!type?.includes?.(\"[]\")) {\n relations.singular.push({\n name: fieldName,\n type: cleanType,\n });\n } else {\n relations.list.push({\n name: fieldName,\n type: cleanType,\n });\n }\n }\n\n prismaModelRelationFields[modelName] = relations;\n }\n }\n}\n\ninitializePrismaModels();\n\n/**\n * Retrieves the relations for a given Prisma model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\").\n * @returns {RelationFields|undefined} The relation fields for the model, or `undefined` if no relations are found.\n */\nexport function getPrismaModelRelations(modelName: string) {\n modelName = pascalCase(modelName);\n\n if (!(modelName in prismaModelRelationFields)) return;\n return prismaModelRelationFields[modelName];\n}\n\n/**\n * Retrieves all the model names from the Prisma schema.\n *\n * @returns {string[]} An array of model names (e.g., [\"User\", \"Post\"]).\n */\nfunction getModels() {\n return models;\n}\n\n/** Retuns a given model unique fields\n * @param {string} modelName - The name of model in PascalCase\n * @returns {string[]} An array of all unique fields,\n */\nfunction getModelUniqueFields(modelName: string) {\n return prismaModelsUniqueFields[modelName];\n}\n\nexport { getModels, getModelUniqueFields };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.controller.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.controller.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AAGxD,OAAO,WAAW,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,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,IACE,CAAC,WAAW,CAAC,gBAAgB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;gBAClD,CAAC,OAAO,EAAE,UAAU,EACpB,CAAC;gBACD,OAAO,IAAI,CACT,IAAI,QAAQ,CACV,eAAe,EAAE,kBAAkB,EAAE,OAAO;oBAC1C,mGAAmG,EACrG,GAAG,CACJ,CACF,CAAC;YACJ,CAAC;YAGD,MAAM,WAAW,CAAC,SAAS,CACzB,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,EACf;gBACE,QAAQ,EAAE,MAAM,WAAW,CAAC,YAAY,CAAC,WAAW,CAAC;gBACrD,iBAAiB,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;aACxC,CACF,CAAC;YAEF,IAAI,WAAW,EAAE,mBAAmB,EAAE,CAAC;gBACrC,GAAG,CAAC,cAAc,GAAG;oBACnB,IAAI;iBACL,CAAC;gBACF,GAAG,CAAC,YAAY,GAAG;oBACjB,MAAM,EAAE,SAAS;oBACjB,OAAO,EAAE,gCAAgC;iBAC1C,CAAC;gBACF,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC;gBACzB,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACnB,MAAM,EAAE,SAAS;gBACjB,OAAO,EAAE,gCAAgC;aAC1C,CAAC,CAAC;QACL,CAAC,CACF;KACF,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { CookieOptions } from \"express\";\nimport { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport authService from \"./auth.service\";\nimport { getBaseServices } from \"../base/base.service\";\nimport { User } from \"../../types\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getArkosConfig } from \"../../server\";\nimport {\n createPrismaWhereClause,\n determineUsernameField,\n getNestedValue,\n MsDuration,\n toMs,\n} from \"./utils/helpers/auth.controller.helpers\";\n\n/**\n * Default fields to exclude from user object when returning to client\n */\nexport const defaultExcludedUserFields = {\n password: false,\n};\n\n/**\n * Factory function to create authentication controller with configurable middlewares\n *\n * @param middlewares - Optional middleware functions to execute after controller actions\n * @returns An object containing all authentication controller methods\n */\nexport const authControllerFactory = async (middlewares: any = {}) => {\n const userService = getBaseServices()[\"user\"];\n let prismaQueryOptions: Record<string, any> = {};\n\n const userModules = await importPrismaModelModules(\"user\");\n if (userModules) prismaQueryOptions = userModules?.prismaQueryOptions || {};\n\n return {\n /**\n * Retrieves the current authenticated user's information\n */\n getMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = await userService.findOne(\n { id: req.user!.id },\n req.prismaQueryOptions || {}\n );\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (middlewares?.afterGetMe) {\n req.responseData = { data: user };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Updates the current authenticated user's information\n */\n updateMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (\"password\" in req.body)\n throw new AppError(\n \"In order to update password use the update-password endpoint.\",\n 400,\n {},\n \"invalid_field_password\"\n );\n\n const user = await userService.updateOne(\n { id: req.user!.id },\n req.body,\n req.prismaQueryOptions || {}\n );\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (middlewares?.afterGetMe) {\n req.responseData = { data: user };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Logs out the current user by invalidating their access token cookie\n */\n logout: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n res.cookie(\"arkos_access_token\", \"no-token\", {\n expires: new Date(Date.now() + 10 * 1000),\n httpOnly: true,\n });\n\n if (middlewares?.afterLogout) {\n req.responseData = null;\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n }\n ),\n\n /**\n * Authenticates a user using configurable username field and password\n * Username field can be specified in query parameter or config\n * Supports nested fields and array queries (e.g., \"profile.nickname\", \"phones.some.number\")\n */\n login: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const authConfigs = getArkosConfig()?.authentication;\n\n const usernameField = determineUsernameField(req);\n\n // For the error message, we only care about the top-level field name\n const lastField =\n usernameField.split(\".\")[usernameField.split(\".\").length - 1];\n\n const usernameValue = req.body[lastField];\n\n const { password } = req.body;\n\n if (!usernameValue || !password)\n return next(\n new AppError(`Please provide both ${lastField} and password`, 400)\n );\n\n // Create appropriate where clause for the query\n let whereClause: Record<string, any>;\n\n if (usernameField?.includes?.(\".\")) {\n // For nested paths, we need to extract the actual value to search for\n const valueToFind = getNestedValue(req.body, usernameField);\n if (valueToFind === undefined) {\n return next(new AppError(`Invalid ${usernameField} provided`, 400));\n }\n whereClause = createPrismaWhereClause(usernameField, valueToFind);\n } else {\n // Simple field case\n whereClause = { [usernameField]: usernameValue };\n }\n\n // Use findFirst instead of findUnique for complex queries\n const user = await userService.findOne(\n whereClause,\n req.prismaQueryOptions || {}\n );\n\n if (\n !user ||\n !(await authService.isCorrectPassword(password, user.password))\n ) {\n return next(new AppError(`Incorrect ${lastField} or password`, 401));\n }\n\n const token = authService.signJwtToken(user.id!);\n\n const cookieOptions: CookieOptions = {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ||\n process.env.JWT_COOKIE_HTTP_ONLY === \"true\" ||\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ||\n process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\",\n sameSite:\n authConfigs?.jwt?.cookie?.sameSite ||\n process.env.JWT_COOKIE_SAME_SITE ||\n process.env.NODE_ENV === \"production\"\n ? \"none\"\n : \"lax\",\n };\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n req.responseData = { accessToken: token };\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.cookie(\"arkos_access_token\", token, cookieOptions);\n\n if (middlewares?.afterLogin) {\n req.additionalData = { user };\n req.responseStatus = 200;\n return next();\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n res.status(200).json(req.responseData);\n } else if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.status(200).send();\n }\n ),\n\n /**\n * Creates a new user account using the userService\n */\n signup: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = await userService.createOne(\n req.body,\n req.prismaQueryOptions || {}\n );\n\n if (middlewares?.afterSignup) {\n req.responseData = { data: user };\n req.responseStatus = 201;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete user[key as keyof User];\n });\n\n res.status(201).json({ data: user });\n }\n ),\n /**\n * Marks user account as self-deleted by setting deletedSelfAccountAt timestamp\n */\n deleteMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const userId = req.user!.id; // Assuming the authenticated user's ID is available in req.user\n\n const updatedUser = await userService.updateOne(\n { id: userId },\n {\n deletedSelfAccountAt: new Date().toISOString(),\n },\n req.prismaQueryOptions || {}\n );\n\n if (middlewares?.afterDeleteMe) {\n req.responseData = { data: updatedUser };\n req.responseStatus = 200;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete updatedUser[key as keyof User];\n });\n\n res.status(200).json({\n message: \"Account deleted successfully\",\n });\n }\n ),\n\n /**\n * Updates the password of the authenticated user\n */\n updatePassword: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const { currentPassword, newPassword } = req.body;\n\n if (!currentPassword || !newPassword)\n return next(\n new AppError(\"currentPassword and newPassword are required\", 400)\n );\n\n const user = req.user;\n\n if (!user || user?.isActive === false || user?.deletedSelfAccountAt)\n return next(new AppError(\"User not found!\", 404));\n\n // Check if the current password is correct\n const isPasswordCorrect = await authService.isCorrectPassword(\n String(currentPassword),\n String(user.password)\n );\n\n const configs = getArkosConfig();\n const initAuthConfigs = configs?.authentication;\n // const modules = getModelModules(\"auth\");\n\n if (!isPasswordCorrect)\n return next(new AppError(\"Current password is incorrect.\", 400));\n\n // Check password strength (optional but recommended)\n if (\n !authService.isPasswordStrong(String(newPassword)) &&\n !configs?.validation\n ) {\n return next(\n new AppError(\n initAuthConfigs?.passwordValidation?.message ||\n \"The new password must contain at least one uppercase letter, one lowercase letter, and one number\",\n 400\n )\n );\n }\n\n // Update the password\n await userService.updateOne(\n { id: user.id },\n {\n password: await authService.hashPassword(newPassword),\n passwordChangedAt: new Date(Date.now()),\n }\n );\n\n if (middlewares?.afterUpdatePassword) {\n req.additionalData = {\n user,\n };\n req.responseData = {\n status: \"success\",\n message: \"Password updated successfully!\",\n };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({\n status: \"success\",\n message: \"Password updated successfully!\",\n });\n }\n ),\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"auth.controller.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.controller.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AAGxD,OAAO,WAAW,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAE9E,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,cAAc,EAEd,IAAI,GACL,MAAM,yCAAyC,CAAC;AAKjD,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACvC,QAAQ,EAAE,KAAK;CAChB,CAAC;AAQF,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,EAAE,cAAmB,EAAE,EAAE,EAAE;IACnE,MAAM,WAAW,GAAG,eAAe,EAAE,CAAC,MAAM,CAAC,CAAC;IAC9C,IAAI,kBAAkB,GAAwB,EAAE,CAAC;IAEjD,MAAM,WAAW,GAAG,MAAM,wBAAwB,CAAC,MAAM,CAAC,CAAC;IAC3D,IAAI,WAAW;QAAE,kBAAkB,GAAG,WAAW,EAAE,kBAAkB,IAAI,EAAE,CAAC;IAE5E,OAAO;QAIL,KAAK,EAAE,UAAU,CACf,KAAK,EACH,GAAiB,EACjB,GAAkB,EAClB,IAAuB,EACvB,EAAE;YACF,MAAM,IAAI,GAAG,MAAM,WAAW,CAAC,OAAO,CACpC,EAAE,EAAE,EAAE,GAAG,CAAC,IAAK,CAAC,EAAE,EAAE,EACpB,GAAG,CAAC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E,gCAAgC;aAC1C,CAAC,CAAC;QACL,CAAC,CACF;KACF,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { CookieOptions } from \"express\";\nimport { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport authService from \"./auth.service\";\nimport { getBaseServices } from \"../base/base.service\";\nimport { User } from \"../../types\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getArkosConfig } from \"../../server\";\nimport {\n createPrismaWhereClause,\n determineUsernameField,\n getNestedValue,\n MsDuration,\n toMs,\n} from \"./utils/helpers/auth.controller.helpers\";\n\n/**\n * Default fields to exclude from user object when returning to client\n */\nexport const defaultExcludedUserFields = {\n password: false,\n};\n\n/**\n * Factory function to create authentication controller with configurable middlewares\n *\n * @param middlewares - Optional middleware functions to execute after controller actions\n * @returns An object containing all authentication controller methods\n */\nexport const authControllerFactory = async (middlewares: any = {}) => {\n const userService = getBaseServices()[\"user\"];\n let prismaQueryOptions: Record<string, any> = {};\n\n const userModules = await importPrismaModelModules(\"user\");\n if (userModules) prismaQueryOptions = userModules?.prismaQueryOptions || {};\n\n return {\n /**\n * Retrieves the current authenticated user's information\n */\n getMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = await userService.findOne(\n { id: req.user!.id },\n req.prismaQueryOptions || {}\n );\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (middlewares?.afterGetMe) {\n req.responseData = { data: user };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Updates the current authenticated user's information\n */\n updateMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (\"password\" in req.body)\n throw new AppError(\n \"In order to update password use the update-password endpoint.\",\n 400,\n {},\n \"invalid_field_password\"\n );\n\n const user = await userService.updateOne(\n { id: req.user!.id },\n req.body,\n req.prismaQueryOptions || {}\n );\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (middlewares?.afterGetMe) {\n req.responseData = { data: user };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Logs out the current user by invalidating their access token cookie\n */\n logout: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n res.cookie(\"arkos_access_token\", \"no-token\", {\n expires: new Date(Date.now() + 10 * 1000),\n httpOnly: true,\n });\n\n if (middlewares?.afterLogout) {\n req.responseData = null;\n req.responseStatus = 204;\n return next();\n }\n\n res.status(204).json();\n }\n ),\n\n /**\n * Authenticates a user using configurable username field and password\n * Username field can be specified in query parameter or config\n * Supports nested fields and array queries (e.g., \"profile.nickname\", \"phones.some.number\")\n */\n login: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const authConfigs = getArkosConfig()?.authentication;\n\n const usernameField = determineUsernameField(req);\n\n // For the error message, we only care about the top-level field name\n const lastField =\n usernameField.split(\".\")[usernameField.split(\".\").length - 1];\n\n const usernameValue = req.body[lastField];\n\n const { password } = req.body;\n\n if (!usernameValue || !password)\n return next(\n new AppError(`Please provide both ${lastField} and password`, 400)\n );\n\n // Create appropriate where clause for the query\n let whereClause: Record<string, any>;\n\n if (usernameField?.includes?.(\".\")) {\n // For nested paths, we need to extract the actual value to search for\n const valueToFind = getNestedValue(req.body, usernameField);\n if (valueToFind === undefined) {\n return next(new AppError(`Invalid ${usernameField} provided`, 400));\n }\n whereClause = createPrismaWhereClause(usernameField, valueToFind);\n } else {\n // Simple field case\n whereClause = { [usernameField]: usernameValue };\n }\n\n // Use findFirst instead of findUnique for complex queries\n const user = await userService.findOne(\n whereClause,\n req.prismaQueryOptions || {}\n );\n\n if (\n !user ||\n !(await authService.isCorrectPassword(password, user.password))\n ) {\n return next(new AppError(`Incorrect ${lastField} or password`, 401));\n }\n\n const token = authService.signJwtToken(user.id!);\n\n const cookieOptions: CookieOptions = {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ||\n process.env.JWT_COOKIE_HTTP_ONLY === \"true\" ||\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ||\n process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\",\n sameSite:\n authConfigs?.jwt?.cookie?.sameSite ||\n process.env.JWT_COOKIE_SAME_SITE ||\n process.env.NODE_ENV === \"production\"\n ? \"none\"\n : \"lax\",\n };\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n req.responseData = { accessToken: token };\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.cookie(\"arkos_access_token\", token, cookieOptions);\n\n if (middlewares?.afterLogin) {\n req.additionalData = { user };\n req.responseStatus = 200;\n return next();\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n res.status(200).json(req.responseData);\n } else if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.status(200).send();\n }\n ),\n\n /**\n * Creates a new user account using the userService\n */\n signup: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = await userService.createOne(\n req.body,\n req.prismaQueryOptions || {}\n );\n\n if (middlewares?.afterSignup) {\n req.responseData = { data: user };\n req.responseStatus = 201;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete user[key as keyof User];\n });\n\n res.status(201).json({ data: user });\n }\n ),\n /**\n * Marks user account as self-deleted by setting deletedSelfAccountAt timestamp\n */\n deleteMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const userId = req.user!.id; // Assuming the authenticated user's ID is available in req.user\n\n const updatedUser = await userService.updateOne(\n { id: userId },\n {\n deletedSelfAccountAt: new Date().toISOString(),\n },\n req.prismaQueryOptions || {}\n );\n\n if (middlewares?.afterDeleteMe) {\n req.responseData = { data: updatedUser };\n req.responseStatus = 200;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete updatedUser[key as keyof User];\n });\n\n res.status(200).json({\n message: \"Account deleted successfully\",\n });\n }\n ),\n\n /**\n * Updates the password of the authenticated user\n */\n updatePassword: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const { currentPassword, newPassword } = req.body;\n\n if (!currentPassword || !newPassword)\n return next(\n new AppError(\"currentPassword and newPassword are required\", 400)\n );\n\n const user = req.user;\n\n if (!user || user?.isActive === false || user?.deletedSelfAccountAt)\n return next(new AppError(\"User not found!\", 404));\n\n // Check if the current password is correct\n const isPasswordCorrect = await authService.isCorrectPassword(\n String(currentPassword),\n String(user.password)\n );\n\n const configs = getArkosConfig();\n const initAuthConfigs = configs?.authentication;\n // const modules = getModelModules(\"auth\");\n\n if (!isPasswordCorrect)\n return next(new AppError(\"Current password is incorrect.\", 400));\n\n // Check password strength (optional but recommended)\n if (\n !authService.isPasswordStrong(String(newPassword)) &&\n !configs?.validation\n ) {\n return next(\n new AppError(\n initAuthConfigs?.passwordValidation?.message ||\n \"The new password must contain at least one uppercase letter, one lowercase letter, and one number\",\n 400\n )\n );\n }\n\n // Update the password\n await userService.updateOne(\n { id: user.id },\n {\n password: await authService.hashPassword(newPassword),\n passwordChangedAt: new Date(Date.now()),\n }\n );\n\n if (middlewares?.afterUpdatePassword) {\n req.additionalData = {\n user,\n };\n req.responseData = {\n status: \"success\",\n message: \"Password updated successfully!\",\n };\n req.responseStatus = 200;\n return next();\n }\n\n res.status(200).json({\n status: \"success\",\n message: \"Password updated successfully!\",\n });\n }\n ),\n };\n};\n"]}
|
|
@@ -9,7 +9,7 @@ import pluralize from "pluralize";
|
|
|
9
9
|
export class BaseController {
|
|
10
10
|
constructor(modelName) {
|
|
11
11
|
this.createOne = catchAsync(async (req, res, next) => {
|
|
12
|
-
const data = await this.
|
|
12
|
+
const data = await this.service.createOne(req.body, req.prismaQueryOptions);
|
|
13
13
|
if (this.middlewares.afterCreateOne) {
|
|
14
14
|
req.responseData = { data };
|
|
15
15
|
req.responseStatus = 201;
|
|
@@ -18,7 +18,7 @@ export class BaseController {
|
|
|
18
18
|
res.status(201).json({ data });
|
|
19
19
|
});
|
|
20
20
|
this.createMany = catchAsync(async (req, res, next) => {
|
|
21
|
-
const data = await this.
|
|
21
|
+
const data = await this.service.createMany(req.body, req.prismaQueryOptions);
|
|
22
22
|
if (!data) {
|
|
23
23
|
return next(new AppError("Failed to create the resources. Please check your input.", 400));
|
|
24
24
|
}
|
|
@@ -30,7 +30,7 @@ export class BaseController {
|
|
|
30
30
|
res.status(201).json({ data });
|
|
31
31
|
});
|
|
32
32
|
this.findMany = catchAsync(async (req, res, next) => {
|
|
33
|
-
const { filters: { where, ...queryOptions }, } = new APIFeatures(req, this.modelName, this.
|
|
33
|
+
const { filters: { where, ...queryOptions }, } = new APIFeatures(req, this.modelName, this.service.relationFields?.singular.reduce((acc, curr) => {
|
|
34
34
|
acc[curr.name] = true;
|
|
35
35
|
return acc;
|
|
36
36
|
}, {}))
|
|
@@ -39,8 +39,8 @@ export class BaseController {
|
|
|
39
39
|
.limitFields()
|
|
40
40
|
.paginate();
|
|
41
41
|
const [data, total] = await Promise.all([
|
|
42
|
-
this.
|
|
43
|
-
this.
|
|
42
|
+
this.service.findMany(where, queryOptions),
|
|
43
|
+
this.service.count(where),
|
|
44
44
|
]);
|
|
45
45
|
if (this.middlewares.afterFindMany) {
|
|
46
46
|
req.responseData = { total, results: data.length, data };
|
|
@@ -50,7 +50,7 @@ export class BaseController {
|
|
|
50
50
|
res.status(200).json({ total, results: data.length, data });
|
|
51
51
|
});
|
|
52
52
|
this.findOne = catchAsync(async (req, res, next) => {
|
|
53
|
-
const data = await this.
|
|
53
|
+
const data = await this.service.findOne(req.params, req.prismaQueryOptions);
|
|
54
54
|
if (!data) {
|
|
55
55
|
if (Object.keys(req.params).length === 1 &&
|
|
56
56
|
"id" in req.params &&
|
|
@@ -69,7 +69,7 @@ export class BaseController {
|
|
|
69
69
|
res.status(200).json({ data });
|
|
70
70
|
});
|
|
71
71
|
this.updateOne = catchAsync(async (req, res, next) => {
|
|
72
|
-
const data = await this.
|
|
72
|
+
const data = await this.service.updateOne(req.params, req.body, req.prismaQueryOptions);
|
|
73
73
|
if (!data) {
|
|
74
74
|
if (Object.keys(req.params).length === 1 && "id" in req.params) {
|
|
75
75
|
return next(new AppError(`${pascalCase(String(this.modelName))} with ID ${req.params?.id} not found`, 404, {}, "not_found"));
|
|
@@ -92,7 +92,7 @@ export class BaseController {
|
|
|
92
92
|
req.query.filterMode = req.query?.filterMode || "AND";
|
|
93
93
|
const features = new APIFeatures(req, this.modelName).filter().sort();
|
|
94
94
|
delete features.filters.include;
|
|
95
|
-
const data = await this.
|
|
95
|
+
const data = await this.service.updateMany(features.filters, req.body, req.prismaQueryOptions);
|
|
96
96
|
if (!data || data.count === 0) {
|
|
97
97
|
return next(new AppError(`${pluralize(pascalCase(String(this.modelName)))} not found`, 404));
|
|
98
98
|
}
|
|
@@ -104,7 +104,7 @@ export class BaseController {
|
|
|
104
104
|
res.status(200).json({ results: data.count, data });
|
|
105
105
|
});
|
|
106
106
|
this.deleteOne = catchAsync(async (req, res, next) => {
|
|
107
|
-
const data = await this.
|
|
107
|
+
const data = await this.service.deleteOne(req.params);
|
|
108
108
|
if (!data) {
|
|
109
109
|
if (Object.keys(req.params).length === 1 && "id" in req.params) {
|
|
110
110
|
return next(new AppError(`${pascalCase(String(this.modelName))} with ID ${req.params?.id} not found`, 404, {}, "not_found"));
|
|
@@ -125,9 +125,8 @@ export class BaseController {
|
|
|
125
125
|
return next(new AppError("Filter criteria not provided for bulk deletion.", 400));
|
|
126
126
|
}
|
|
127
127
|
req.query.filterMode = req.query?.filterMode || "AND";
|
|
128
|
-
const { filters: { where
|
|
129
|
-
|
|
130
|
-
const data = await this.baseService.deleteMany(where);
|
|
128
|
+
const { filters: { where }, } = new APIFeatures(req, this.modelName).filter().sort();
|
|
129
|
+
const data = await this.service.deleteMany(where);
|
|
131
130
|
if (!data || data.count === 0) {
|
|
132
131
|
return next(new AppError(`No records found to delete`, 404));
|
|
133
132
|
}
|
|
@@ -139,7 +138,7 @@ export class BaseController {
|
|
|
139
138
|
res.status(200).json({ results: data.count, data });
|
|
140
139
|
});
|
|
141
140
|
this.modelName = modelName;
|
|
142
|
-
this.
|
|
141
|
+
this.service = new BaseService(modelName);
|
|
143
142
|
this.middlewares = getModelModules(modelName)?.middlewares || {};
|
|
144
143
|
}
|
|
145
144
|
}
|
|
@@ -1 +1 @@
|
|
|
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;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,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WAAW,CAAC,SAAS,CAAC,CAAC;QAC9C,IAAI,CAAC,WAAW,GAAG,eAAe,CAAC,SAAS,CAAC,EAAE,WAAW,IAAI,EAAE,CAAC;IACnE,CAAC;CAyUF;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 */\nexport class BaseController {\n /**\n * Service instance to handle business logic operations\n * @private\n */\n private baseService: 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.baseService = 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.baseService.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.baseService.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.baseService.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.baseService.findMany(where, queryOptions),\n this.baseService.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.baseService.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.baseService.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.baseService.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.baseService.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, ...queryOptions },\n } = new APIFeatures(req, this.modelName).filter().sort();\n\n console.log(where, queryOptions);\n\n const data = await this.baseService.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;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,QAAQ,MAAM,kCAAkC,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;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"]}
|