arkos 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/cjs/app.js +1 -1
  2. package/dist/cjs/app.js.map +1 -1
  3. package/dist/cjs/exports/index.js.map +1 -1
  4. package/dist/cjs/modules/auth/auth.controller.js +37 -24
  5. package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
  6. package/dist/cjs/modules/auth/auth.router.js +5 -4
  7. package/dist/cjs/modules/auth/auth.router.js.map +1 -1
  8. package/dist/cjs/modules/auth/auth.service.js +2 -2
  9. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  10. package/dist/cjs/modules/auth/utils/helpers/auth.controller.helpers.js +88 -0
  11. package/dist/cjs/modules/auth/utils/helpers/auth.controller.helpers.js.map +1 -0
  12. package/dist/cjs/modules/base/base.router.js +5 -65
  13. package/dist/cjs/modules/base/base.router.js.map +1 -1
  14. package/dist/cjs/modules/base/base.service.js +3 -3
  15. package/dist/cjs/modules/base/base.service.js.map +1 -1
  16. package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +112 -0
  17. package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -0
  18. package/dist/cjs/modules/base/utils/helpers/{base.helpers.js → base.service.helpers.js} +1 -1
  19. package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -0
  20. package/dist/cjs/modules/file-uploader/file-uploader.router.js +3 -3
  21. package/dist/cjs/modules/file-uploader/file-uploader.router.js.map +1 -1
  22. package/dist/cjs/types/arkos-config.js.map +1 -1
  23. package/dist/cjs/types/auth.js.map +1 -1
  24. package/dist/cjs/types/{prisma-model-router-config.js → router-config.js} +1 -1
  25. package/dist/cjs/types/router-config.js.map +1 -0
  26. package/dist/cjs/utils/arkos-env.js +0 -1
  27. package/dist/cjs/utils/arkos-env.js.map +1 -1
  28. package/dist/cjs/utils/helpers/base.controller.helpers.js.map +1 -1
  29. package/dist/cjs/utils/helpers/models.helpers.js +82 -127
  30. package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
  31. package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
  32. package/dist/es2020/app.js +1 -1
  33. package/dist/es2020/app.js.map +1 -1
  34. package/dist/es2020/exports/index.js.map +1 -1
  35. package/dist/es2020/modules/auth/auth.controller.js +36 -23
  36. package/dist/es2020/modules/auth/auth.controller.js.map +1 -1
  37. package/dist/es2020/modules/auth/auth.router.js +5 -4
  38. package/dist/es2020/modules/auth/auth.router.js.map +1 -1
  39. package/dist/es2020/modules/auth/auth.service.js +2 -2
  40. package/dist/es2020/modules/auth/auth.service.js.map +1 -1
  41. package/dist/es2020/modules/auth/utils/helpers/auth.controller.helpers.js +78 -0
  42. package/dist/es2020/modules/auth/utils/helpers/auth.controller.helpers.js.map +1 -0
  43. package/dist/es2020/modules/base/base.router.js +7 -67
  44. package/dist/es2020/modules/base/base.router.js.map +1 -1
  45. package/dist/es2020/modules/base/base.service.js +1 -1
  46. package/dist/es2020/modules/base/base.service.js.map +1 -1
  47. package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js +106 -0
  48. package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js.map +1 -0
  49. package/dist/es2020/modules/base/utils/helpers/{base.helpers.js → base.service.helpers.js} +1 -1
  50. package/dist/es2020/modules/base/utils/helpers/base.service.helpers.js.map +1 -0
  51. package/dist/es2020/modules/file-uploader/file-uploader.router.js +3 -3
  52. package/dist/es2020/modules/file-uploader/file-uploader.router.js.map +1 -1
  53. package/dist/es2020/types/arkos-config.js.map +1 -1
  54. package/dist/es2020/types/auth.js.map +1 -1
  55. package/dist/es2020/types/router-config.js +2 -0
  56. package/dist/es2020/types/router-config.js.map +1 -0
  57. package/dist/es2020/utils/arkos-env.js +0 -1
  58. package/dist/es2020/utils/arkos-env.js.map +1 -1
  59. package/dist/es2020/utils/helpers/base.controller.helpers.js.map +1 -1
  60. package/dist/es2020/utils/helpers/models.helpers.js +82 -127
  61. package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
  62. package/dist/es2020/utils/helpers/prisma.helpers.js.map +1 -1
  63. package/dist/types/exports/index.d.ts +2 -2
  64. package/dist/types/modules/auth/auth.service.d.ts +3 -3
  65. package/dist/types/modules/auth/utils/helpers/auth.controller.helpers.d.ts +6 -0
  66. package/dist/types/modules/base/base.router.d.ts +2 -1
  67. package/dist/types/modules/base/utils/helpers/base.router.helpers.d.ts +2 -0
  68. package/dist/types/types/arkos-config.d.ts +10 -6
  69. package/dist/types/types/auth.d.ts +1 -1
  70. package/dist/types/types/{prisma-model-router-config.d.ts → router-config.d.ts} +4 -4
  71. package/dist/types/utils/arkos-env.d.ts +0 -1
  72. package/dist/types/utils/helpers/base.controller.helpers.d.ts +6 -2
  73. package/dist/types/utils/helpers/models.helpers.d.ts +10 -24
  74. package/package.json +1 -1
  75. package/dist/cjs/modules/auth/utils/helpers/auth.helpers.js +0 -19
  76. package/dist/cjs/modules/auth/utils/helpers/auth.helpers.js.map +0 -1
  77. package/dist/cjs/modules/base/utils/helpers/base.helpers.js.map +0 -1
  78. package/dist/cjs/types/prisma-model-router-config.js.map +0 -1
  79. package/dist/es2020/modules/auth/utils/helpers/auth.helpers.js +0 -12
  80. package/dist/es2020/modules/auth/utils/helpers/auth.helpers.js.map +0 -1
  81. package/dist/es2020/modules/base/utils/helpers/base.helpers.js.map +0 -1
  82. package/dist/es2020/types/prisma-model-router-config.js +0 -2
  83. package/dist/es2020/types/prisma-model-router-config.js.map +0 -1
  84. package/dist/types/modules/auth/utils/helpers/auth.helpers.d.ts +0 -2
  85. /package/dist/types/modules/base/utils/helpers/{base.helpers.d.ts → base.service.helpers.d.ts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import 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 { SignOptions } from \"jsonwebtoken\";\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 /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\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 /** 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 /** 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 * 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 usernameField?: string;\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 * 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 * Defines jwt configurations for secret, expiresIn, cookieExpiresIn\n *\n * Can be pass also through env variables:\n * - jwt.secret => JWT_SECRET: If not passed production auth will throw an error\n * - jwt.expiresIn => JWT_EXPIRES_IN: default 30d\n * - jwt.cookieExpiresIn => JWT_COOKIE_EXPIRES_IN: default 90\n * - jwt.secure => JWT_SECURE: default true\n *\n * **Note**: the values passed here will take precedence\n */\n jwt?: {\n /** Secret to sign and decode jwt tokens */\n secret?: string;\n /**\n * Do define when the toke expires\n */\n expiresIn?: SignOptions[\"expiresIn\"];\n /** Days in which the cookie must be kept before expire*/\n cookieExpiresIn?: number;\n /** If it must be secure or not, Default: true */\n secure?: boolean;\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 *\n windowMs: 60 * 1000,\n limit: 1000,\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 * 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 additionals?: 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 additionals?: 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/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/accessing-the-express-app](https://www.arkosjs.com/docs/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 * 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 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 { SignOptions } from \"jsonwebtoken\";\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 /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\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/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/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 * @deprecated\n *\n * **Use this instead**:\n *\n * ```ts\n * arkos.init({\n * authentication: {\n * login: {\n * allowedUsernames: [\"email\", \"profile.nickname\"]\n * }\n * }\n * })\n * ```\n *\n * * See more at [www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n */\n usernameField?: string;\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 * 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_EXPIRES_IN`: Defaults to 90 (used for calculating cookie expiration).\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 *\n windowMs: 60 * 1000,\n limit: 1000,\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 * 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/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/accessing-the-express-app](https://www.arkosjs.com/docs/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 * 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":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Possible actions that can be performed by a controller.\n */\nexport type ControllerActions = \"create\" | \"update\" | \"delete\" | \"view\";\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AccessControlRules = {\n /**\n * Maps each `ControllerAction` to the roles allowed to perform it.\n */\n [key in ControllerActions]: any[];\n};\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AuthenticationControlRules = {\n /**\n * Maps each `ControllerAction` to the actions that requires authentication to perform it.\n */\n [key in ControllerActions]: boolean;\n};\n\n/**\n * Configuration for authentication and access control.\n */\nexport type AuthConfigs = {\n /**\n * Defines access control rules for roles or actions.\n *\n * @type {Role | Role[] | AccessControlRules}\n */\n authenticationControl?: boolean | Partial<AuthenticationControlRules>;\n /**\n * List of user roles, or restricted by actions\n */\n accessControl?: any[] | Partial<AccessControlRules>;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n */\nexport interface AuthJwtPayload extends JwtPayload {\n /**\n * The unique identifier of the authenticated user.\n *\n * @type {number | string}\n */\n id?: number | string;\n\n /**\n * The username of the authenticated user.\n *\n * @type {string}\n */\n username?: string;\n}\n"]}
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Possible actions that can be performed by a controller.\n */\nexport type ControllerActions = \"create\" | \"update\" | \"delete\" | \"view\";\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AccessControlRules = {\n /**\n * Maps each `ControllerAction` to the roles allowed to perform it.\n */\n [key in ControllerActions]: any[];\n};\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AuthenticationControlRules = {\n /**\n * Maps each `ControllerAction` to the actions that requires authentication to perform it.\n */\n [key in ControllerActions]: boolean;\n};\n\n/**\n * Configuration for authentication and access control.\n */\nexport type AuthConfigs = {\n /**\n * Defines access control rules for roles or actions.\n *\n * @type {Role | Role[] | AccessControlRules}\n */\n authenticationControl?: boolean | Partial<AuthenticationControlRules>;\n /**\n * List of user roles, or restricted by actions\n */\n accessControl?: any[] | Partial<AccessControlRules>;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n */\nexport interface AuthJwtPayload extends JwtPayload {\n /**\n * The unique identifier of the authenticated user.\n *\n * @type {number | string}\n */\n id?: number | string;\n\n [x: string]: any;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=router-config.js.map
@@ -0,0 +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/advanced-guide/customizing-prisma-models-routers](https://https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-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/advanced-guide/customizing-prisma-models-routers](https://ttps://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-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 foreignKey?: string;\n /**\n * Customizes what endpoints to be created.\n *\n * Default is \"*\" to generate all endpoints\n */\n endpoints?: \"*\" | RouterEndpoint | 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"]}
@@ -1,6 +1,5 @@
1
1
  const arkosEnv = {
2
2
  JWT_SECRET: "13a9279eedb286f756212511267152e9585055809ec0606ea9f7eb98a87660c1616fbd39c44d4238a82f29df90b529e24bfdf72a480d1149d79c991c863a22b5ae0fb3ae6f5323bfd6664faef99792637477c38da488e7aa0d39b83ba99aba8e8a20efde7fd5c7ba21a6c938e17a9f99f73226dc61e89cd63f159257841194323f100d1a49b88ce4fdcdf2b066a5f32f88ee12f6487b55b4b5687d7c0caffdd8524e2adc4b941cf52e948f5b330f527eb1354341c876eed12dfa92cef3c341d030d05e6beb1e0a7f6d3e08e7b1aac045130457fd3a53ee469fecdd20fdd2c7a6a72b07cbcb1157c5b1cc581e6767bea32be8e125016a48951e85c7bdb961d9c9fab28444499ce063664fe0bd1a05d60294323bdd69af6d6ff1a2533dac8d4a869f76dbc746ee12f144e0af41029f620471817843140c23d036e731f3ebee21a70ff1549e97486fdf9cbef132ff2ced59fde9be35dd04b358c9a25ec4fd9cc0e36dae651e626d8c13b0c6d2a21f237517a05059680173e71817597062c792ea9c66030ca0d8ed82987e29189947692a0be5fffac4c988ca33f14ce96349661ef850dbff6909c7797676c90a5e47655346f59759482ef8a3a948e97e30f889bd4571610fd19e8ea4818651d37f6529cf32f0fc805bc053e911f0fe96f52b4420d54bd1f40739a95f5853b036c86ab9a51bed57fa9bd48607b5302e88db00900adf",
3
- JWT_COOKIE_EXPIRES_IN: 90,
4
3
  JWT_EXPIRES_IN: "30d",
5
4
  PRISMA_SCHEMA_PATH: `./prisma/schema`,
6
5
  };
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-env.js","sourceRoot":"","sources":["../../../src/utils/arkos-env.ts"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAAG;IACf,UAAU,EACR,kgCAAkgC;IACpgC,qBAAqB,EAAE,EAAE;IACzB,cAAc,EAAE,KAAK;IACrB,kBAAkB,EAAE,iBAAiB;CACtC,CAAC;AAEF,eAAe,QAAQ,CAAC","sourcesContent":["const arkosEnv = {\n JWT_SECRET:\n \"13a9279eedb286f756212511267152e9585055809ec0606ea9f7eb98a87660c1616fbd39c44d4238a82f29df90b529e24bfdf72a480d1149d79c991c863a22b5ae0fb3ae6f5323bfd6664faef99792637477c38da488e7aa0d39b83ba99aba8e8a20efde7fd5c7ba21a6c938e17a9f99f73226dc61e89cd63f159257841194323f100d1a49b88ce4fdcdf2b066a5f32f88ee12f6487b55b4b5687d7c0caffdd8524e2adc4b941cf52e948f5b330f527eb1354341c876eed12dfa92cef3c341d030d05e6beb1e0a7f6d3e08e7b1aac045130457fd3a53ee469fecdd20fdd2c7a6a72b07cbcb1157c5b1cc581e6767bea32be8e125016a48951e85c7bdb961d9c9fab28444499ce063664fe0bd1a05d60294323bdd69af6d6ff1a2533dac8d4a869f76dbc746ee12f144e0af41029f620471817843140c23d036e731f3ebee21a70ff1549e97486fdf9cbef132ff2ced59fde9be35dd04b358c9a25ec4fd9cc0e36dae651e626d8c13b0c6d2a21f237517a05059680173e71817597062c792ea9c66030ca0d8ed82987e29189947692a0be5fffac4c988ca33f14ce96349661ef850dbff6909c7797676c90a5e47655346f59759482ef8a3a948e97e30f889bd4571610fd19e8ea4818651d37f6529cf32f0fc805bc053e911f0fe96f52b4420d54bd1f40739a95f5853b036c86ab9a51bed57fa9bd48607b5302e88db00900adf\",\n JWT_COOKIE_EXPIRES_IN: 90,\n JWT_EXPIRES_IN: \"30d\",\n PRISMA_SCHEMA_PATH: `./prisma/schema`,\n};\n\nexport default arkosEnv;\n"]}
1
+ {"version":3,"file":"arkos-env.js","sourceRoot":"","sources":["../../../src/utils/arkos-env.ts"],"names":[],"mappings":"AAAA,MAAM,QAAQ,GAAG;IACf,UAAU,EACR,kgCAAkgC;IACpgC,cAAc,EAAE,KAAK;IACrB,kBAAkB,EAAE,iBAAiB;CACtC,CAAC;AAEF,eAAe,QAAQ,CAAC","sourcesContent":["const arkosEnv = {\n JWT_SECRET:\n \"13a9279eedb286f756212511267152e9585055809ec0606ea9f7eb98a87660c1616fbd39c44d4238a82f29df90b529e24bfdf72a480d1149d79c991c863a22b5ae0fb3ae6f5323bfd6664faef99792637477c38da488e7aa0d39b83ba99aba8e8a20efde7fd5c7ba21a6c938e17a9f99f73226dc61e89cd63f159257841194323f100d1a49b88ce4fdcdf2b066a5f32f88ee12f6487b55b4b5687d7c0caffdd8524e2adc4b941cf52e948f5b330f527eb1354341c876eed12dfa92cef3c341d030d05e6beb1e0a7f6d3e08e7b1aac045130457fd3a53ee469fecdd20fdd2c7a6a72b07cbcb1157c5b1cc581e6767bea32be8e125016a48951e85c7bdb961d9c9fab28444499ce063664fe0bd1a05d60294323bdd69af6d6ff1a2533dac8d4a869f76dbc746ee12f144e0af41029f620471817843140c23d036e731f3ebee21a70ff1549e97486fdf9cbef132ff2ced59fde9be35dd04b358c9a25ec4fd9cc0e36dae651e626d8c13b0c6d2a21f237517a05059680173e71817597062c792ea9c66030ca0d8ed82987e29189947692a0be5fffac4c988ca33f14ce96349661ef850dbff6909c7797676c90a5e47655346f59759482ef8a3a948e97e30f889bd4571610fd19e8ea4818651d37f6529cf32f0fc805bc053e911f0fe96f52b4420d54bd1f40739a95f5853b036c86ab9a51bed57fa9bd48607b5302e88db00900adf\",\n JWT_EXPIRES_IN: \"30d\",\n PRISMA_SCHEMA_PATH: `./prisma/schema`,\n};\n\nexport default arkosEnv;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"base.controller.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/base.controller.helpers.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAE9C,OAAO,WAAW,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,cAAc,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAEzD,MAAM,UAAU,4CAA4C,CAC1D,SAAiB,EACjB,MAA2B;IAE3B,OAAO,UAAU,CACf,CAAO,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;;QACvE,MAAM,YAAY,GAAG,eAAe,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;QAC3D,MAAM,iBAAiB,GAAG,MAAA,cAAc,EAAE,0CAAE,UAAU,CAAC;QACvD,IAAI,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;QAEpB,IACE,CAAA,iBAAiB,aAAjB,iBAAiB,uBAAjB,iBAAiB,CAAE,QAAQ,MAAK,iBAAiB;YACjD,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC;YAEzB,GAAG,CAAC,IAAI,GAAG,MAAM,WAAW,CAC1B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,EACzB,IAAI,EACJ,SAAS,CACP;gBACE,SAAS,EAAE,IAAI;aAChB,EACD,CAAA,iBAAiB,aAAjB,iBAAiB,uBAAjB,iBAAiB,CAAE,iBAAiB,KAAI,EAAE,CAC3C,CACF,CAAC;aACC,IACH,CAAA,iBAAiB,aAAjB,iBAAiB,uBAAjB,iBAAiB,CAAE,QAAQ,MAAK,KAAK;YACrC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC;YAE5B,GAAG,CAAC,IAAI,GAAG,MAAM,cAAc,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;QAEtE,IAAI,EAAE,CAAC;IACT,CAAC,CAAA,CACF,CAAC;AACJ,CAAC","sourcesContent":["import deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { getArkosConfig } from \"../../server\";\nimport { ArkosNextFunction, ArkosRequest, ArkosResponse } from \"../../types\";\nimport validateDto from \"../validate-dto\";\nimport { kebabCase } from \"./change-case.helpers\";\nimport { getModelModules } from \"./models.helpers\";\nimport validateSchema from \"../validate-schema\";\nimport { catchAsync } from \"../../exports/error-handler\";\n\nexport function handleRequestBodyValidationAndTransformation(\n modelName: string,\n action: \"create\" | \"update\"\n) {\n return catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const modelModules = getModelModules(kebabCase(modelName));\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (\n validationConfigs?.resolver === \"class-validator\" &&\n modelModules.dtos[action]\n )\n req.body = await validateDto(\n modelModules.dtos[action],\n body,\n deepmerge(\n {\n whitelist: true,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (\n validationConfigs?.resolver === \"zod\" &&\n modelModules.schemas[action]\n )\n req.body = await validateSchema(modelModules.schemas[action], body);\n\n next();\n }\n );\n}\n"]}
1
+ {"version":3,"file":"base.controller.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/base.controller.helpers.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAO9C,OAAO,WAAW,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,cAAc,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAkBzD,MAAM,UAAU,4CAA4C,CAC1D,SAAiB,EACjB,MAAc;IAEd,OAAO,UAAU,CACf,CAAO,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;;QACvE,MAAM,YAAY,GAAG,eAAe,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;QAC3D,MAAM,iBAAiB,GAAG,MAAA,cAAc,EAAE,0CAAE,UAAU,CAAC;QACvD,IAAI,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;QAEpB,IACE,CAAA,iBAAiB,aAAjB,iBAAiB,uBAAjB,iBAAiB,CAAE,QAAQ,MAAK,iBAAiB;YACjD,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC;YAEzB,GAAG,CAAC,IAAI,GAAG,MAAM,WAAW,CAC1B,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,EACzB,IAAI,EACJ,SAAS,CACP;gBACE,SAAS,EAAE,IAAI;aAChB,EACD,CAAA,iBAAiB,aAAjB,iBAAiB,uBAAjB,iBAAiB,CAAE,iBAAiB,KAAI,EAAE,CAC3C,CACF,CAAC;aACC,IACH,CAAA,iBAAiB,aAAjB,iBAAiB,uBAAjB,iBAAiB,CAAE,QAAQ,MAAK,KAAK;YACrC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC;YAE5B,GAAG,CAAC,IAAI,GAAG,MAAM,cAAc,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;QAEtE,IAAI,EAAE,CAAC;IACT,CAAC,CAAA,CACF,CAAC;AACJ,CAAC","sourcesContent":["import deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { getArkosConfig } from \"../../server\";\nimport {\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n} from \"../../types\";\nimport validateDto from \"../validate-dto\";\nimport { kebabCase } from \"./change-case.helpers\";\nimport { getModelModules } from \"./models.helpers\";\nimport validateSchema from \"../validate-schema\";\nimport { catchAsync } from \"../../exports/error-handler\";\n\ntype AuthActions = \"signup\" | \"login\" | \"updateMe\" | \"updatePassword\";\ntype DefaultActions = \"create\" | \"update\";\n\n// Overload for 'auth'\nexport function handleRequestBodyValidationAndTransformation(\n modelName: \"auth\",\n action: AuthActions\n): ArkosRequestHandler;\n\n// Overload for other models\nexport function handleRequestBodyValidationAndTransformation(\n modelName: Exclude<string, \"auth\">,\n action: DefaultActions\n): ArkosRequestHandler;\n\n// Implementation\nexport function handleRequestBodyValidationAndTransformation(\n modelName: string,\n action: string\n) {\n return catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const modelModules = getModelModules(kebabCase(modelName));\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (\n validationConfigs?.resolver === \"class-validator\" &&\n modelModules.dtos[action]\n )\n req.body = await validateDto(\n modelModules.dtos[action],\n body,\n deepmerge(\n {\n whitelist: true,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (\n validationConfigs?.resolver === \"zod\" &&\n modelModules.schemas[action]\n )\n req.body = await validateSchema(modelModules.schemas[action], body);\n\n next();\n }\n );\n}\n"]}
@@ -18,141 +18,97 @@ export function getModelModules(modelName) {
18
18
  }
19
19
  export function importPrismaModelModules(modelName) {
20
20
  return __awaiter(this, void 0, void 0, function* () {
21
- const kebabModelName = kebabCase(modelName);
22
- const lowerModelName = modelName.toLowerCase();
21
+ const kebabModelName = kebabCase(modelName).toLowerCase();
22
+ const lowerModelName = kebabModelName.toLowerCase();
23
+ const pascalModelName = pascalCase(modelName);
23
24
  const moduleDir = path.resolve(process.cwd(), "src", "modules", modelName);
24
- const dtosDir = path.join(moduleDir, "dtos");
25
- const schemasDir = path.join(moduleDir, "schemas");
26
- const middlewaresFile = path.join(moduleDir, `${kebabModelName}.middlewares.${userFileExtension}`);
27
- const authConfigsFile = path.join(moduleDir, `${kebabModelName}.auth-configs.${userFileExtension}`);
28
- const prismaQueryOptionsFile = path.join(moduleDir, `${kebabModelName}.prisma-query-options.${userFileExtension}`);
29
- const modelDtoFile = path.join(dtosDir, `${lowerModelName}.dto.${userFileExtension}`);
30
- const createDtoFile = path.join(dtosDir, `create-${lowerModelName}.dto.${userFileExtension}`);
31
- const updateDtoFile = path.join(dtosDir, `update-${lowerModelName}.dto.${userFileExtension}`);
32
- const queryDtoFile = path.join(dtosDir, `query-${lowerModelName}.dto.${userFileExtension}`);
33
- const modelSchemaFile = path.join(schemasDir, `${lowerModelName}.schema.${userFileExtension}`);
34
- const createSchemaFile = path.join(schemasDir, `create-${lowerModelName}.schema.${userFileExtension}`);
35
- const updateSchemaFile = path.join(schemasDir, `update-${lowerModelName}.schema.${userFileExtension}`);
36
- const querySchemaFile = path.join(schemasDir, `query-${lowerModelName}.schema.${userFileExtension}`);
25
+ const isAuthModule = modelName.toLowerCase() === "auth";
26
+ const fileStructure = {
27
+ core: {
28
+ service: `${kebabModelName}.service.${userFileExtension}`,
29
+ controller: `${kebabModelName}.controller.${userFileExtension}`,
30
+ middlewares: `${kebabModelName}.middlewares.${userFileExtension}`,
31
+ authConfigs: `${kebabModelName}.auth-configs.${userFileExtension}`,
32
+ prismaQueryOptions: `${kebabModelName}.prisma-query-options.${userFileExtension}`,
33
+ router: `${kebabModelName}.router.${userFileExtension}`,
34
+ },
35
+ dtos: isAuthModule
36
+ ? {
37
+ login: `login.dto.${userFileExtension}`,
38
+ signup: `signup.dto.${userFileExtension}`,
39
+ updateMe: `update-me.dto.${userFileExtension}`,
40
+ updatePassword: `update-password.dto.${userFileExtension}`,
41
+ }
42
+ : {
43
+ model: `${lowerModelName}.dto.${userFileExtension}`,
44
+ create: `create-${lowerModelName}.dto.${userFileExtension}`,
45
+ update: `update-${lowerModelName}.dto.${userFileExtension}`,
46
+ query: `query-${lowerModelName}.dto.${userFileExtension}`,
47
+ },
48
+ schemas: isAuthModule
49
+ ? {
50
+ login: `login.schema.${userFileExtension}`,
51
+ signup: `signup.schema.${userFileExtension}`,
52
+ updateMe: `update-me.schema.${userFileExtension}`,
53
+ updatePassword: `update-password.schema.${userFileExtension}`,
54
+ }
55
+ : {
56
+ model: `${lowerModelName}.schema.${userFileExtension}`,
57
+ create: `create-${lowerModelName}.schema.${userFileExtension}`,
58
+ update: `update-${lowerModelName}.schema.${userFileExtension}`,
59
+ query: `query-${lowerModelName}.schema.${userFileExtension}`,
60
+ },
61
+ };
37
62
  const result = {
38
63
  dtos: {},
39
64
  schemas: {},
40
65
  };
41
- try {
42
- if (fs.existsSync(middlewaresFile)) {
43
- const middlewareModule = yield import(middlewaresFile);
44
- result.middlewares = middlewareModule;
45
- }
46
- }
47
- catch (error) {
48
- console.error(`Error importing middlewares for model "${modelName}":`, error);
49
- }
50
- try {
51
- if (fs.existsSync(authConfigsFile)) {
52
- const authConfigsModule = yield import(authConfigsFile);
53
- result.authConfigs = authConfigsModule.default || authConfigsModule;
66
+ yield Promise.all(Object.entries(fileStructure.core).map((_a) => __awaiter(this, [_a], void 0, function* ([key, fileName]) {
67
+ const filePath = path.join(moduleDir, fileName);
68
+ try {
69
+ const module = yield import(filePath).catch(() => null);
70
+ if (module) {
71
+ if (key === "middlewares")
72
+ result[key] = module;
73
+ else
74
+ result[key] = module.default || module;
75
+ }
54
76
  }
55
- }
56
- catch (error) {
57
- console.error(`Error importing auth configs for model "${modelName}":`, error);
58
- }
59
- try {
60
- if (fs.existsSync(prismaQueryOptionsFile)) {
61
- const prismaQueryOptionsModule = yield import(prismaQueryOptionsFile);
62
- result.prismaQueryOptions =
63
- prismaQueryOptionsModule.default || prismaQueryOptionsModule;
64
- }
65
- }
66
- catch (error) {
67
- console.error(`Error importing prisma query options for model "${modelName}":`, error);
68
- }
69
- const pascalModelName = pascalCase(modelName);
70
- try {
71
- if (fs.existsSync(modelDtoFile)) {
72
- const modelDtoModule = yield import(modelDtoFile);
73
- result.dtos.model =
74
- modelDtoModule.default || modelDtoModule[`${pascalModelName}Dto`];
75
- }
76
- }
77
- catch (error) {
78
- console.error(`Error importing model main DTO for model "${modelName} ${pascalModelName}":`, error);
79
- }
80
- try {
81
- if (fs.existsSync(createDtoFile)) {
82
- const createDtoModule = yield import(createDtoFile);
83
- result.dtos.create =
84
- createDtoModule.default ||
85
- createDtoModule[`Create${pascalModelName}Dto`];
86
- }
87
- }
88
- catch (error) {
89
- console.error(`Error importing create DTO for model "${modelName}":`, error);
90
- }
91
- try {
92
- if (fs.existsSync(updateDtoFile)) {
93
- const updateDtoModule = yield import(updateDtoFile);
94
- result.dtos.update =
95
- updateDtoModule.default ||
96
- updateDtoModule[`Update${pascalModelName}Dto`];
77
+ catch (error) {
97
78
  }
98
- }
99
- catch (error) {
100
- console.error(`Error importing update DTO for model "${modelName}":`, error);
101
- }
102
- try {
103
- if (fs.existsSync(queryDtoFile)) {
104
- const queryDtoModule = yield import(queryDtoFile);
105
- result.dtos.query =
106
- queryDtoModule.default || queryDtoModule[`Query${pascalModelName}Dto`];
107
- }
108
- }
109
- catch (error) {
110
- console.error(`Error importing query DTO for model "${modelName}":`, error);
111
- }
112
- try {
113
- if (fs.existsSync(modelSchemaFile)) {
114
- const modelSchemaModule = yield import(modelSchemaFile);
115
- result.dtos.model =
116
- modelSchemaModule.default ||
117
- modelSchemaModule[`${pascalModelName}Schema`];
118
- }
119
- }
120
- catch (error) {
121
- console.error(`Error importing create Schema for model "${modelName}":`, error);
122
- }
123
- try {
124
- if (fs.existsSync(createSchemaFile)) {
125
- const createSchemaModule = yield import(createSchemaFile);
126
- result.dtos.create =
127
- createSchemaModule.default ||
128
- createSchemaModule[`Create${pascalModelName}Schema`];
129
- }
130
- }
131
- catch (error) {
132
- console.error(`Error importing create Schema for model "${modelName}":`, error);
133
- }
134
- try {
135
- if (fs.existsSync(updateSchemaFile)) {
136
- const updateSchemaModule = yield import(updateSchemaFile);
137
- result.dtos.update =
138
- updateSchemaModule.default ||
139
- updateSchemaModule[`Update${pascalModelName}Schema`];
79
+ })));
80
+ const processSubdir = (type) => __awaiter(this, void 0, void 0, function* () {
81
+ const subdir = path.join(moduleDir, type);
82
+ try {
83
+ yield fs.promises.access(subdir).catch(() => {
84
+ return;
85
+ });
86
+ yield Promise.all(Object.entries(fileStructure[type]).map((_a) => __awaiter(this, [_a], void 0, function* ([key, fileName]) {
87
+ const filePath = path.join(subdir, fileName);
88
+ try {
89
+ const module = yield import(filePath).catch(() => null);
90
+ if (module) {
91
+ if (isAuthModule) {
92
+ const pascalKey = key.charAt(0).toUpperCase() + key.slice(1);
93
+ const expectedName = `${pascalKey}${type === "dtos" ? "Dto" : "Schema"}`;
94
+ result[type][key] = module.default;
95
+ }
96
+ else {
97
+ const expectedName = key === "model"
98
+ ? `${pascalModelName}${type === "dtos" ? "Dto" : "Schema"}`
99
+ : `${key.charAt(0).toUpperCase() + key.slice(1)}${pascalModelName}${type === "dtos" ? "Dto" : "Schema"}`;
100
+ result[type][key] = module.default;
101
+ }
102
+ }
103
+ }
104
+ catch (error) {
105
+ }
106
+ })));
140
107
  }
141
- }
142
- catch (error) {
143
- console.error(`Error importing update Schema for model "${modelName}":`, error);
144
- }
145
- try {
146
- if (fs.existsSync(querySchemaFile)) {
147
- const querySchemaModule = yield import(querySchemaFile);
148
- result.dtos.query =
149
- querySchemaModule.default ||
150
- querySchemaModule[`Query${pascalModelName}Schema`];
108
+ catch (error) {
151
109
  }
152
- }
153
- catch (error) {
154
- console.error(`Error importing query Schema for model "${modelName}":`, error);
155
- }
110
+ });
111
+ yield Promise.all([processSubdir("dtos"), processSubdir("schemas")]);
156
112
  prismaModelsModules[modelName] = result;
157
113
  return result;
158
114
  });
@@ -268,7 +224,6 @@ export function getPrismaModelRelations(modelName) {
268
224
  return prismaModelRelationFields[modelName];
269
225
  }
270
226
  function getModels() {
271
- console.log(models);
272
227
  return models;
273
228
  }
274
229
  function getModelUniqueFields(modelName) {
@@ -1 +1 @@
1
- {"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,GACX,MAAM,yCAAyC,CAAC;AACjD,OAAO,QAAQ,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEjD,MAAM,CAAC,IAAI,mBAAmB,GAG1B,EAAE,CAAC;AAEP,MAAM,UAAU,eAAe,CAAC,SAAiB;IAC/C,OAAO,mBAAmB,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AASD,MAAM,UAAgB,wBAAwB,CAAC,SAAiB;;QAC9D,MAAM,cAAc,GAAG,S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,KAAK,SAAS;gBACvB,SAAS,KAAK,UAAU;gBACxB,SAAS,KAAK,OAAO;gBACrB,SAAS,KAAK,SAAS;gBACvB,SAAS,KAAK,QAAQ;gBACtB,SAAS,KAAK,MAAM,EACpB,CAAC;gBACD,SAAS;YACX,CAAC;YAED,IAAI,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,QAAQ,CAAC,IAAI,CAAC,CAAA,EAAE,CAAC;gBAC1B,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;oBACtB,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,SAAS;iBAChB,CAAC,CAAC;YACL,CAAC;iBAAM,CAAC;gBACN,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;oBAClB,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,SAAS;iBAChB,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,yBAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;IACnD,CAAC;AACH,CAAC;AAQD,MAAM,UAAU,uBAAuB,CAAC,SAAiB;IACvD,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;IAElC,IAAI,CAAC,CAAC,SAAS,IAAI,yBAAyB,CAAC;QAAE,OAAO;IACtD,OAAO,yBAAyB,CAAC,SAAS,CAAC,CAAC;AAC9C,CAAC;AAOD,SAAS,SAAS;IAChB,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACpB,OAAO,MAAM,CAAC;AAChB,CAAC;AAMD,SAAS,oBAAoB,CAAC,SAAiB;IAC7C,OAAO,wBAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,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 arkosEnv from \"../arkos-env\";\nimport { userFileExtension } from \"./fs.helpers\";\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\n/**\n * Dynamically imports model-specific modules like middlewares, auth configurations,\n * prisma query options, and DTOs for a given model.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\").\n * @returns {Promise<Object>} An object containing the imported modules: `middlewares`, `authConfigs`, `prismaQueryOptions`, and `dtos`.\n */\nexport async function importPrismaModelModules(modelName: string) {\n const kebabModelName = kebabCase(modelName);\n const lowerModelName = modelName.toLowerCase();\n\n const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n const dtosDir = path.join(moduleDir, \"dtos\");\n const schemasDir = path.join(moduleDir, \"schemas\");\n\n const middlewaresFile = path.join(\n moduleDir,\n `${kebabModelName}.middlewares.${userFileExtension}`\n );\n const authConfigsFile = path.join(\n moduleDir,\n `${kebabModelName}.auth-configs.${userFileExtension}`\n );\n const prismaQueryOptionsFile = path.join(\n moduleDir,\n `${kebabModelName}.prisma-query-options.${userFileExtension}`\n );\n\n // Define DTO file paths\n const modelDtoFile = path.join(\n dtosDir,\n `${lowerModelName}.dto.${userFileExtension}`\n );\n const createDtoFile = path.join(\n dtosDir,\n `create-${lowerModelName}.dto.${userFileExtension}`\n );\n const updateDtoFile = path.join(\n dtosDir,\n `update-${lowerModelName}.dto.${userFileExtension}`\n );\n const queryDtoFile = path.join(\n dtosDir,\n `query-${lowerModelName}.dto.${userFileExtension}`\n );\n\n const modelSchemaFile = path.join(\n schemasDir,\n `${lowerModelName}.schema.${userFileExtension}`\n );\n const createSchemaFile = path.join(\n schemasDir,\n `create-${lowerModelName}.schema.${userFileExtension}`\n );\n const updateSchemaFile = path.join(\n schemasDir,\n `update-${lowerModelName}.schema.${userFileExtension}`\n );\n const querySchemaFile = path.join(\n schemasDir,\n `query-${lowerModelName}.schema.${userFileExtension}`\n );\n\n const result: {\n middlewares?: any;\n authConfigs?: any;\n prismaQueryOptions?: any;\n dtos: {\n create?: any;\n update?: any;\n query?: any;\n model?: any;\n };\n schemas: {\n create?: any;\n update?: any;\n query?: any;\n model?: any;\n };\n } = {\n dtos: {},\n schemas: {},\n };\n\n try {\n if (fs.existsSync(middlewaresFile)) {\n const middlewareModule = await import(middlewaresFile);\n result.middlewares = middlewareModule;\n }\n } catch (error) {\n console.error(\n `Error importing middlewares for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(authConfigsFile)) {\n const authConfigsModule = await import(authConfigsFile);\n result.authConfigs = authConfigsModule.default || authConfigsModule;\n }\n } catch (error) {\n console.error(\n `Error importing auth configs for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(prismaQueryOptionsFile)) {\n const prismaQueryOptionsModule = await import(prismaQueryOptionsFile);\n result.prismaQueryOptions =\n prismaQueryOptionsModule.default || prismaQueryOptionsModule;\n }\n } catch (error) {\n console.error(\n `Error importing prisma query options for model \"${modelName}\":`,\n error\n );\n }\n\n // Import DTOs\n const pascalModelName = pascalCase(modelName);\n try {\n if (fs.existsSync(modelDtoFile)) {\n const modelDtoModule = await import(modelDtoFile);\n result.dtos.model =\n modelDtoModule.default || modelDtoModule[`${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(\n `Error importing model main DTO for model \"${modelName} ${pascalModelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(createDtoFile)) {\n const createDtoModule = await import(createDtoFile);\n result.dtos.create =\n createDtoModule.default ||\n createDtoModule[`Create${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(\n `Error importing create DTO for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(updateDtoFile)) {\n const updateDtoModule = await import(updateDtoFile);\n result.dtos.update =\n updateDtoModule.default ||\n updateDtoModule[`Update${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(\n `Error importing update DTO for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(queryDtoFile)) {\n const queryDtoModule = await import(queryDtoFile);\n result.dtos.query =\n queryDtoModule.default || queryDtoModule[`Query${pascalModelName}Dto`];\n }\n } catch (error) {\n console.error(`Error importing query DTO for model \"${modelName}\":`, error);\n }\n\n try {\n if (fs.existsSync(modelSchemaFile)) {\n const modelSchemaModule = await import(modelSchemaFile);\n result.dtos.model =\n modelSchemaModule.default ||\n modelSchemaModule[`${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing create Schema for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(createSchemaFile)) {\n const createSchemaModule = await import(createSchemaFile);\n result.dtos.create =\n createSchemaModule.default ||\n createSchemaModule[`Create${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing create Schema for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(updateSchemaFile)) {\n const updateSchemaModule = await import(updateSchemaFile);\n result.dtos.update =\n updateSchemaModule.default ||\n updateSchemaModule[`Update${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing update Schema for model \"${modelName}\":`,\n error\n );\n }\n\n try {\n if (fs.existsSync(querySchemaFile)) {\n const querySchemaModule = await import(querySchemaFile);\n result.dtos.query =\n querySchemaModule.default ||\n querySchemaModule[`Query${pascalModelName}Schema`];\n }\n } catch (error) {\n console.error(\n `Error importing query Schema for model \"${modelName}\":`,\n error\n );\n }\n\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\nconst schemaFolderPath =\n process.env.PRISMA_SCHEMA_PATH || arkosEnv.PRISMA_SCHEMA_PATH;\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 */\nconst prismaModelRelationFields: Record<string, RelationFields> = {};\n\nconst prismaContent: string[] = [];\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\n// const prismaRootDir = \"\"; // Adjust this path if needed\nconst files = getAllPrismaFiles(\"./prisma\");\n\nfor (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n prismaContent.push(content);\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nconst models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nprismaContent.join(\"\\n\").replace(modelRegex, (_, modelName) => {\n if (!models.includes(modelName)) models.push(camelCase(modelName.trim()));\n return modelName;\n});\n\nfor (const model of models) {\n const modelName = pascalCase(model);\n\n let modelFile;\n for (const file of files) {\n const filePath = path.join(file);\n const stats = fs.statSync(filePath);\n\n if (stats.isFile()) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n prismaContent.push(content);\n if (content.includes(`model ${modelName} {`)) {\n modelFile = file;\n break;\n }\n }\n }\n\n if (!modelFile) {\n throw new Error(`Model ${modelName} not found`);\n }\n\n const content = fs.readFileSync(path.join(modelFile), \"utf-8\");\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 prismaModelsUniqueFields[model] = [\n ...(prismaModelsUniqueFields[model] || []),\n { name: fieldName, type, isUnique },\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 modelStart = content.indexOf(`enum ${cleanType} {`);\n\n if (\n !cleanType ||\n modelStart >= 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 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/**\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 console.log(models);\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 { models, getModels, getModelUniqueFields, prismaModelRelationFields };\n"]}
1
+ {"version":3,"file":"models.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/models.helpers.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,GACX,MAAM,yCAAyC,CAAC;AACjD,OAAO,QAAQ,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEjD,MAAM,CAAC,IAAI,mBAAmB,GAG1B,EAAE,CAAC;AAEP,MAAM,UAAU,eAAe,CAAC,SAAiB;IAC/C,OAAO,mBAAmB,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;AACnD,CAAC;AAoPD,MAAM,UAAgB,wBAAwB,CAAC,SAAiB;;QAC9D,MAAM,cAAc,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC;QAC1D,MAAM,cAAc,GAAG,cAAc,CAAC,WAAW,EAAE,CAAC;QACpD,MAAM,eAAe,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;QAE9C,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;QAG3E,MAAM,YAAY,GAAG,SAAS,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;QAGxD,MAAM,aAAa,GAAG;YACpB,IAAI,EAAE;gBACJ,OAAO,EAAE,GAAG,cAAc,YAAY,iBAAiB,EAAE;gBACzD,UAAU,EAAE,GAAG,cAAc,eAAe,iBAAiB,EAAE;gBAC/D,WAAW,EAAE,GAAG,cAAc,gBA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AC7C,OAAO,wBAAwB,CAAC,SAAS,CAAC,CAAC;AAC7C,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,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 arkosEnv from \"../arkos-env\";\nimport { userFileExtension } from \"./fs.helpers\";\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\n// /**\n// * Dynamically imports model-specific modules like middlewares, auth configurations,\n// * prisma query options, and DTOs for a given model.\n// *\n// * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\").\n// * @returns {Promise<Object>} An object containing the imported modules: `middlewares`, `authConfigs`, `prismaQueryOptions`, and `dtos`.\n// */\n// export async function importPrismaModelModules(modelName: string) {\n// const kebabModelName = kebabCase(modelName);\n// const lowerModelName = modelName.toLowerCase();\n\n// const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n// const dtosDir = path.join(moduleDir, \"dtos\");\n// const schemasDir = path.join(moduleDir, \"schemas\");\n\n// const middlewaresFile = path.join(\n// moduleDir,\n// `${kebabModelName}.middlewares.${userFileExtension}`\n// );\n// const authConfigsFile = path.join(\n// moduleDir,\n// `${kebabModelName}.auth-configs.${userFileExtension}`\n// );\n// const prismaQueryOptionsFile = path.join(\n// moduleDir,\n// `${kebabModelName}.prisma-query-options.${userFileExtension}`\n// );\n\n// // Define DTO file paths\n// const modelDtoFile = path.join(\n// dtosDir,\n// `${lowerModelName}.dto.${userFileExtension}`\n// );\n// const createDtoFile = path.join(\n// dtosDir,\n// `create-${lowerModelName}.dto.${userFileExtension}`\n// );\n// const updateDtoFile = path.join(\n// dtosDir,\n// `update-${lowerModelName}.dto.${userFileExtension}`\n// );\n// const queryDtoFile = path.join(\n// dtosDir,\n// `query-${lowerModelName}.dto.${userFileExtension}`\n// );\n\n// const modelSchemaFile = path.join(\n// schemasDir,\n// `${lowerModelName}.schema.${userFileExtension}`\n// );\n// const createSchemaFile = path.join(\n// schemasDir,\n// `create-${lowerModelName}.schema.${userFileExtension}`\n// );\n// const updateSchemaFile = path.join(\n// schemasDir,\n// `update-${lowerModelName}.schema.${userFileExtension}`\n// );\n// const querySchemaFile = path.join(\n// schemasDir,\n// `query-${lowerModelName}.schema.${userFileExtension}`\n// );\n\n// const result: {\n// middlewares?: any;\n// authConfigs?: any;\n// prismaQueryOptions?: any;\n// dtos: {\n// create?: any;\n// update?: any;\n// query?: any;\n// model?: any;\n// };\n// schemas: {\n// create?: any;\n// update?: any;\n// query?: any;\n// model?: any;\n// };\n// } = {\n// dtos: {},\n// schemas: {},\n// };\n\n// try {\n// if (fs.existsSync(middlewaresFile)) {\n// const middlewareModule = await import(middlewaresFile);\n// result.middlewares = middlewareModule;\n// }\n// } catch (error) {\n// console.error(\n// `Error importing middlewares for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(authConfigsFile)) {\n// const authConfigsModule = await import(authConfigsFile);\n// result.authConfigs = authConfigsModule.default || authConfigsModule;\n// }\n// } catch (error) {\n// console.error(\n// `Error importing auth configs for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(prismaQueryOptionsFile)) {\n// const prismaQueryOptionsModule = await import(prismaQueryOptionsFile);\n// result.prismaQueryOptions =\n// prismaQueryOptionsModule.default || prismaQueryOptionsModule;\n// }\n// } catch (error) {\n// console.error(\n// `Error importing prisma query options for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// // Import DTOs\n// const pascalModelName = pascalCase(modelName);\n// try {\n// if (fs.existsSync(modelDtoFile)) {\n// const modelDtoModule = await import(modelDtoFile);\n// result.dtos.model =\n// modelDtoModule.default || modelDtoModule[`${pascalModelName}Dto`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing model main DTO for model \"${modelName} ${pascalModelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(createDtoFile)) {\n// const createDtoModule = await import(createDtoFile);\n// result.dtos.create =\n// createDtoModule.default ||\n// createDtoModule[`Create${pascalModelName}Dto`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing create DTO for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(updateDtoFile)) {\n// const updateDtoModule = await import(updateDtoFile);\n// result.dtos.update =\n// updateDtoModule.default ||\n// updateDtoModule[`Update${pascalModelName}Dto`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing update DTO for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(queryDtoFile)) {\n// const queryDtoModule = await import(queryDtoFile);\n// result.dtos.query =\n// queryDtoModule.default || queryDtoModule[`Query${pascalModelName}Dto`];\n// }\n// } catch (error) {\n// console.error(`Error importing query DTO for model \"${modelName}\":`, error);\n// }\n\n// try {\n// if (fs.existsSync(modelSchemaFile)) {\n// const modelSchemaModule = await import(modelSchemaFile);\n// result.dtos.model =\n// modelSchemaModule.default ||\n// modelSchemaModule[`${pascalModelName}Schema`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing create Schema for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(createSchemaFile)) {\n// const createSchemaModule = await import(createSchemaFile);\n// result.dtos.create =\n// createSchemaModule.default ||\n// createSchemaModule[`Create${pascalModelName}Schema`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing create Schema for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(updateSchemaFile)) {\n// const updateSchemaModule = await import(updateSchemaFile);\n// result.dtos.update =\n// updateSchemaModule.default ||\n// updateSchemaModule[`Update${pascalModelName}Schema`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing update Schema for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// try {\n// if (fs.existsSync(querySchemaFile)) {\n// const querySchemaModule = await import(querySchemaFile);\n// result.dtos.query =\n// querySchemaModule.default ||\n// querySchemaModule[`Query${pascalModelName}Schema`];\n// }\n// } catch (error) {\n// console.error(\n// `Error importing query Schema for model \"${modelName}\":`,\n// error\n// );\n// }\n\n// prismaModelsModules[modelName] = result;\n\n// return result;\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(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const lowerModelName = kebabModelName.toLowerCase();\n const pascalModelName = pascalCase(modelName);\n\n const moduleDir = path.resolve(process.cwd(), \"src\", \"modules\", modelName);\n\n // Define special auth module structure if needed\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n\n // Define the structure of files to import\n const fileStructure = {\n core: {\n service: `${kebabModelName}.service.${userFileExtension}`,\n controller: `${kebabModelName}.controller.${userFileExtension}`,\n middlewares: `${kebabModelName}.middlewares.${userFileExtension}`,\n authConfigs: `${kebabModelName}.auth-configs.${userFileExtension}`,\n prismaQueryOptions: `${kebabModelName}.prisma-query-options.${userFileExtension}`,\n router: `${kebabModelName}.router.${userFileExtension}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${userFileExtension}`,\n signup: `signup.dto.${userFileExtension}`,\n updateMe: `update-me.dto.${userFileExtension}`,\n updatePassword: `update-password.dto.${userFileExtension}`,\n }\n : {\n model: `${lowerModelName}.dto.${userFileExtension}`,\n create: `create-${lowerModelName}.dto.${userFileExtension}`,\n update: `update-${lowerModelName}.dto.${userFileExtension}`,\n query: `query-${lowerModelName}.dto.${userFileExtension}`,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${userFileExtension}`,\n signup: `signup.schema.${userFileExtension}`,\n updateMe: `update-me.schema.${userFileExtension}`,\n updatePassword: `update-password.schema.${userFileExtension}`,\n }\n : {\n model: `${lowerModelName}.schema.${userFileExtension}`,\n create: `create-${lowerModelName}.schema.${userFileExtension}`,\n update: `update-${lowerModelName}.schema.${userFileExtension}`,\n query: `query-${lowerModelName}.schema.${userFileExtension}`,\n },\n };\n\n // Initialize result object\n const result: {\n service?: any;\n controller?: any;\n middlewares?: any;\n authConfigs?: any;\n prismaQueryOptions?: any;\n router?: any;\n dtos: Record<string, any>;\n schemas: Record<string, any>;\n } = {\n dtos: {},\n schemas: {},\n };\n\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 import(filePath).catch(() => null);\n if (module) {\n // For middlewares, keep the entire module\n if (key === \"middlewares\") result[key] = module;\n // For all other core files, prefer default export\n else result[key as keyof typeof result] = module.default || module;\n }\n } catch (error) {\n // Silent fail - file might not exist\n }\n })\n );\n\n // Process DTOs and schemas in parallel\n const processSubdir = async (type: \"dtos\" | \"schemas\") => {\n const subdir = path.join(moduleDir, type);\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\n // Process both subdirectories in parallel\n await Promise.all([processSubdir(\"dtos\"), processSubdir(\"schemas\")]);\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\nconst schemaFolderPath =\n process.env.PRISMA_SCHEMA_PATH || arkosEnv.PRISMA_SCHEMA_PATH;\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 */\nconst prismaModelRelationFields: Record<string, RelationFields> = {};\n\nconst prismaContent: string[] = [];\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\n// const prismaRootDir = \"\"; // Adjust this path if needed\nconst files = getAllPrismaFiles(\"./prisma\");\n\nfor (const file of files) {\n const content = fs.readFileSync(file, \"utf-8\");\n\n prismaContent.push(content);\n}\n\nconst modelRegex = /model\\s+(\\w+)\\s*{/g;\nconst models: string[] = [];\nexport const prismaModelsUniqueFields: Record<string, ModelFieldDefition[]> =\n [] as any;\n\nprismaContent.join(\"\\n\").replace(modelRegex, (_, modelName) => {\n if (!models.includes(modelName)) models.push(camelCase(modelName.trim()));\n return modelName;\n});\n\nfor (const model of models) {\n const modelName = pascalCase(model);\n\n let modelFile;\n for (const file of files) {\n const filePath = path.join(file);\n const stats = fs.statSync(filePath);\n\n if (stats.isFile()) {\n const content = fs.readFileSync(filePath, \"utf-8\");\n prismaContent.push(content);\n if (content.includes(`model ${modelName} {`)) {\n modelFile = file;\n break;\n }\n }\n }\n\n if (!modelFile) {\n throw new Error(`Model ${modelName} not found`);\n }\n\n const content = fs.readFileSync(path.join(modelFile), \"utf-8\");\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 prismaModelsUniqueFields[model] = [\n ...(prismaModelsUniqueFields[model] || []),\n { name: fieldName, type, isUnique },\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 modelStart = content.indexOf(`enum ${cleanType} {`);\n\n if (\n !cleanType ||\n modelStart >= 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 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/**\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 { models, getModels, getModelUniqueFields, prismaModelRelationFields };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"prisma.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/prisma.helpers.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,UAAU,MAAM,+CAA+C,CAAC;AACvE,OAAO,QAAQ,MAAM,6CAA6C,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEhD,MAAM,CAAC,IAAI,cAAc,GAAQ,IAAI,CAAC;AAEtC,MAAM,UAAgB,gBAAgB,CAAC,CAAU;;QAC/C,IAAI,CAAC,cAAc,EAAE,CAAC;YACpB,IAAI,CAAC;gBACH,IAAI,UAAU,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,qBAAqB,iBAAiB,EAAE,CAAC;gBAE1E,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;oBAC/B,UAAU,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,2BAA2B,iBAAiB,EAAE,CAAC;gBAC9E,CAAC;gBAED,MAAM,YAAY,GAAG,MAAM,YAAY,CAAC,UAAU,CAAC,CAAC;gBACpD,cAAc,GAAG,YAAY,CAAC,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC;gBAG7D,IAAI,CAAC,cAAc;oBAAE,MAAM,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC;YACpD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAEf,MAAM,IAAI,QAAQ,CAAC,qCAAqC,EAAE,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;YAC5E,CAAC;QACH,CAAC;QACD,OAAO,cAAc,CAAC;IACxB,CAAC;CAAA;AAED,MAAM,UAAU,iBAAiB;IAC/B,OAAO,cAAc,CAAC;AACxB,CAAC;AAED,MAAM,CAAC,MAAM,uBAAuB,GAAG,UAAU,CAC/C,CAAO,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IACxD,MAAM,MAAM,GAAG,MAAM,gBAAgB,EAAE,CAAC;IACxC,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,QAAQ,EAAE,CAAC;QACxB,IAAI,EAAE,CAAC;IACT,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IACzC,CAAC;AACH,CAAC,CAAA,CACF,CAAC","sourcesContent":["import fs from \"fs\";\nimport { Request, Response, NextFunction } from \"express\";\nimport catchAsync from \"../../modules/error-handler/utils/catch-async\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { userFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\n\nexport let prismaInstance: any = null;\n\nexport async function loadPrismaModule(a?: string) {\n if (!prismaInstance) {\n try {\n let prismaPath = `${process.cwd()}/src/utils/prisma.${userFileExtension}`;\n\n if (!fs.existsSync(prismaPath)) {\n prismaPath = `${process.cwd()}/src/utils/prisma/index.${userFileExtension}`;\n }\n\n const prismaModule = await importModule(prismaPath);\n prismaInstance = prismaModule.default || prismaModule.prisma;\n // console.log(prismaInstance, prismaModule, a, \"prismaInstance\");\n\n if (!prismaInstance) throw new Error(\"not found\");\n } catch (error) {\n // console.error(`Failed to load prisma.${userFileExtension}:`, error);\n throw new AppError(\"Could not initialize Prisma module.\", 500, { error });\n }\n }\n return prismaInstance;\n}\n\nexport function getPrismaInstance() {\n return prismaInstance;\n}\n\nexport const checkDatabaseConnection = catchAsync(\n async (req: Request, res: Response, next: NextFunction) => {\n const prisma = await loadPrismaModule();\n try {\n await prisma.$connect();\n next();\n } catch (error: any) {\n console.error(\"Database connection error\", error.message);\n next(new AppError(error.message, 503));\n }\n }\n);\n"]}
1
+ {"version":3,"file":"prisma.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/prisma.helpers.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,UAAU,MAAM,+CAA+C,CAAC;AACvE,OAAO,QAAQ,MAAM,6CAA6C,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEhD,MAAM,CAAC,IAAI,cAAc,GAAQ,IAAI,CAAC;AAEtC,MAAM,UAAgB,gBAAgB,CAAC,CAAU;;QAC/C,IAAI,CAAC,cAAc,EAAE,CAAC;YACpB,IAAI,CAAC;gBACH,IAAI,UAAU,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,qBAAqB,iBAAiB,EAAE,CAAC;gBAE1E,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;oBAC/B,UAAU,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,2BAA2B,iBAAiB,EAAE,CAAC;gBAC9E,CAAC;gBAED,MAAM,YAAY,GAAG,MAAM,YAAY,CAAC,UAAU,CAAC,CAAC;gBACpD,cAAc,GAAG,YAAY,CAAC,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC;gBAE7D,IAAI,CAAC,cAAc;oBAAE,MAAM,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC;YACpD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAEf,MAAM,IAAI,QAAQ,CAAC,qCAAqC,EAAE,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;YAC5E,CAAC;QACH,CAAC;QACD,OAAO,cAAc,CAAC;IACxB,CAAC;CAAA;AAED,MAAM,UAAU,iBAAiB;IAC/B,OAAO,cAAc,CAAC;AACxB,CAAC;AAED,MAAM,CAAC,MAAM,uBAAuB,GAAG,UAAU,CAC/C,CAAO,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IACxD,MAAM,MAAM,GAAG,MAAM,gBAAgB,EAAE,CAAC;IACxC,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,QAAQ,EAAE,CAAC;QACxB,IAAI,EAAE,CAAC;IACT,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IACzC,CAAC;AACH,CAAC,CAAA,CACF,CAAC","sourcesContent":["import fs from \"fs\";\nimport { Request, Response, NextFunction } from \"express\";\nimport catchAsync from \"../../modules/error-handler/utils/catch-async\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { userFileExtension } from \"./fs.helpers\";\nimport { importModule } from \"./global.helpers\";\n\nexport let prismaInstance: any = null;\n\nexport async function loadPrismaModule(a?: string) {\n if (!prismaInstance) {\n try {\n let prismaPath = `${process.cwd()}/src/utils/prisma.${userFileExtension}`;\n\n if (!fs.existsSync(prismaPath)) {\n prismaPath = `${process.cwd()}/src/utils/prisma/index.${userFileExtension}`;\n }\n\n const prismaModule = await importModule(prismaPath);\n prismaInstance = prismaModule.default || prismaModule.prisma;\n\n if (!prismaInstance) throw new Error(\"not found\");\n } catch (error) {\n // console.error(`Failed to load prisma.${userFileExtension}:`, error);\n throw new AppError(\"Could not initialize Prisma module.\", 500, { error });\n }\n }\n return prismaInstance;\n}\n\nexport function getPrismaInstance() {\n return prismaInstance;\n}\n\nexport const checkDatabaseConnection = catchAsync(\n async (req: Request, res: Response, next: NextFunction) => {\n const prisma = await loadPrismaModule();\n try {\n await prisma.$connect();\n next();\n } catch (error: any) {\n console.error(\"Database connection error\", error.message);\n next(new AppError(error.message, 503));\n }\n }\n);\n"]}
@@ -1,4 +1,4 @@
1
- import { PrismaModelRouterConfig } from "../types/prisma-model-router-config";
1
+ import { RouterConfig } from "../types/router-config";
2
2
  import { BaseController } from "./../modules/base/base.controller";
3
3
  import { initApp } from "../server";
4
4
  import { ArkosRequest, ArkosResponse, ArkosNextFunction, ArkosRequestHandler } from "../types";
@@ -6,5 +6,5 @@ import { ArkosConfig } from "../types/arkos-config";
6
6
  declare const arkos: {
7
7
  init: typeof initApp;
8
8
  };
9
- export { ArkosRequest, ArkosResponse, ArkosNextFunction, ArkosRequestHandler, BaseController, ArkosConfig, PrismaModelRouterConfig, };
9
+ export { ArkosRequest, ArkosResponse, ArkosNextFunction, ArkosRequestHandler, BaseController, ArkosConfig, RouterConfig, };
10
10
  export default arkos;
@@ -1,9 +1,9 @@
1
- import { SignOptions } from "jsonwebtoken";
2
1
  import { User } from "../../types";
3
2
  import { ArkosRequest, ArkosResponse, ArkosNextFunction, ArkosRequestHandler } from "../../types";
4
3
  import { AuthConfigs, AuthJwtPayload, ControllerActions } from "../../types/auth";
4
+ import { MsDuration } from "./utils/helpers/auth.controller.helpers";
5
5
  declare class AuthService {
6
- signJwtToken(id: number | string, expiresIn?: SignOptions["expiresIn"], secret?: string): string;
6
+ signJwtToken(id: number | string, expiresIn?: MsDuration | number, secret?: string): string;
7
7
  isCorrectPassword(candidatePassword: string, userPassword: string): Promise<boolean>;
8
8
  hashPassword(password: string): Promise<string>;
9
9
  isPasswordStrong(password: string): boolean;
@@ -12,7 +12,7 @@ declare class AuthService {
12
12
  handleActionAccessControl(authConfigs: AuthConfigs, action: ControllerActions, modelName: string): ArkosRequestHandler;
13
13
  getAuthenticatedUser(req: ArkosRequest): Promise<User | null>;
14
14
  authenticate: (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => Promise<void>;
15
- handleAuthenticationControl(authConfigs: AuthConfigs | undefined, action: ControllerActions, modelName: string): ArkosRequestHandler;
15
+ handleAuthenticationControl(authConfigs: AuthConfigs | undefined, action: ControllerActions): ArkosRequestHandler;
16
16
  }
17
17
  declare const authService: AuthService;
18
18
  export default authService;
@@ -0,0 +1,6 @@
1
+ import { ArkosRequest } from "../../../../types";
2
+ export declare const determineUsernameField: (req: ArkosRequest) => string;
3
+ export declare const createPrismaWhereClause: (path: string, value: any) => Record<string, any>;
4
+ export declare const getNestedValue: (obj: any, path: string) => any;
5
+ export type MsDuration = number | `${number}` | `${number}${"ms" | "s" | "m" | "h" | "d" | "w" | "y"}`;
6
+ export declare function toMs(input: number | MsDuration): number;
@@ -1,3 +1,4 @@
1
1
  import { Router } from "express";
2
- export declare function getPrismaModelsRouter(): Promise<Router>;
2
+ import { ArkosConfig } from "../../types/arkos-config";
3
+ export declare function getPrismaModelsRouter(arkosConfigs?: ArkosConfig): Promise<Router>;
3
4
  export declare function getAvailableResourcesAndRoutesRouter(): Router;