arkos 1.1.96-test → 1.1.97-test
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/modules/auth/auth.router.js +82 -35
- package/dist/cjs/modules/auth/auth.router.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +7 -11
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/base.service.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.middlewares.helpers.js +50 -0
- package/dist/cjs/modules/base/utils/helpers/base.middlewares.helpers.js.map +1 -0
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +93 -40
- package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +212 -23
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/es2020/modules/auth/auth.router.js +82 -35
- package/dist/es2020/modules/auth/auth.router.js.map +1 -1
- package/dist/es2020/modules/base/base.middlewares.js +7 -11
- package/dist/es2020/modules/base/base.middlewares.js.map +1 -1
- package/dist/es2020/modules/base/base.service.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.middlewares.helpers.js +44 -0
- package/dist/es2020/modules/base/utils/helpers/base.middlewares.helpers.js.map +1 -0
- package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js +93 -40
- package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
- package/dist/es2020/types/index.js.map +1 -1
- package/dist/es2020/utils/cli/dev.js +207 -23
- package/dist/es2020/utils/cli/dev.js.map +1 -1
- package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
- package/dist/types/modules/base/base.middlewares.d.ts +2 -2
- package/dist/types/modules/base/base.service.d.ts +2 -2
- package/dist/types/modules/base/utils/helpers/base.middlewares.helpers.d.ts +3 -0
- package/dist/types/types/index.d.ts +11 -3
- package/dist/types/utils/cli/dev.d.ts +3 -0
- package/package.json +2 -1
|
@@ -11,6 +11,7 @@ const express_rate_limit_1 = __importDefault(require("express-rate-limit"));
|
|
|
11
11
|
const models_helpers_1 = require("../../utils/helpers/models.helpers");
|
|
12
12
|
const base_middlewares_1 = require("../base/base.middlewares");
|
|
13
13
|
const deepmerge_helper_1 = __importDefault(require("../../utils/helpers/deepmerge.helper"));
|
|
14
|
+
const catch_async_1 = __importDefault(require("../error-handler/utils/catch-async"));
|
|
14
15
|
const router = (0, express_1.Router)();
|
|
15
16
|
async function getAuthRouter(arkosConfigs) {
|
|
16
17
|
const { middlewares, dtos, schemas, prismaQueryOptions } = await (0, models_helpers_1.importPrismaModelModules)("auth");
|
|
@@ -25,22 +26,43 @@ async function getAuthRouter(arkosConfigs) {
|
|
|
25
26
|
}
|
|
26
27
|
return undefined;
|
|
27
28
|
};
|
|
29
|
+
const safeCatchAsync = (middleware) => {
|
|
30
|
+
return middleware ? (0, catch_async_1.default)(middleware) : undefined;
|
|
31
|
+
};
|
|
28
32
|
router
|
|
29
|
-
.get("/users/me", auth_service_1.default.authenticate, (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "getMe"),
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
33
|
+
.get("/users/me", auth_service_1.default.authenticate, (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "getMe"), ...[
|
|
34
|
+
safeCatchAsync(middlewares?.beforeGetMe) || authController.getMe,
|
|
35
|
+
safeCatchAsync(middlewares?.beforeGetMe)
|
|
36
|
+
? authController.getMe
|
|
37
|
+
: safeCatchAsync(middlewares?.afterGetMe) || base_middlewares_1.sendResponse,
|
|
38
|
+
safeCatchAsync(middlewares?.beforeGetMe) &&
|
|
39
|
+
safeCatchAsync(middlewares?.afterGetMe)
|
|
40
|
+
? safeCatchAsync(middlewares?.afterGetMe)
|
|
41
|
+
: base_middlewares_1.sendResponse,
|
|
42
|
+
base_middlewares_1.sendResponse,
|
|
43
|
+
].filter((middleware) => !!middleware))
|
|
44
|
+
.patch("/users/me", auth_service_1.default.authenticate, (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("updateMe")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "updateMe"), ...[
|
|
45
|
+
safeCatchAsync(middlewares?.beforeUpdateMe) || authController.updateMe,
|
|
46
|
+
safeCatchAsync(middlewares?.beforeUpdateMe)
|
|
47
|
+
? authController.updateMe
|
|
48
|
+
: safeCatchAsync(middlewares?.afterUpdateMe) || base_middlewares_1.sendResponse,
|
|
49
|
+
safeCatchAsync(middlewares?.beforeUpdateMe) &&
|
|
50
|
+
safeCatchAsync(middlewares?.afterUpdateMe)
|
|
51
|
+
? safeCatchAsync(middlewares?.afterUpdateMe)
|
|
52
|
+
: base_middlewares_1.sendResponse,
|
|
53
|
+
base_middlewares_1.sendResponse,
|
|
54
|
+
].filter((middleware) => !!middleware))
|
|
55
|
+
.delete("/users/me", auth_service_1.default.authenticate, (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "deleteMe"), ...[
|
|
56
|
+
safeCatchAsync(middlewares?.beforeDeleteMe) || authController.deleteMe,
|
|
57
|
+
safeCatchAsync(middlewares?.beforeDeleteMe)
|
|
58
|
+
? authController.deleteMe
|
|
59
|
+
: safeCatchAsync(middlewares?.afterDeleteMe) || base_middlewares_1.sendResponse,
|
|
60
|
+
safeCatchAsync(middlewares?.beforeDeleteMe) &&
|
|
61
|
+
safeCatchAsync(middlewares?.afterDeleteMe)
|
|
62
|
+
? safeCatchAsync(middlewares?.afterDeleteMe)
|
|
63
|
+
: base_middlewares_1.sendResponse,
|
|
64
|
+
base_middlewares_1.sendResponse,
|
|
65
|
+
].filter((middleware) => !!middleware));
|
|
44
66
|
router.use("/auth", (0, express_rate_limit_1.default)((0, deepmerge_helper_1.default)({
|
|
45
67
|
windowMs: 5000,
|
|
46
68
|
limit: 10,
|
|
@@ -52,26 +74,51 @@ async function getAuthRouter(arkosConfigs) {
|
|
|
52
74
|
});
|
|
53
75
|
},
|
|
54
76
|
}, arkosConfigs?.authentication?.requestRateLimitOptions || {})));
|
|
55
|
-
router.post("/auth/login", (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("login")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "login"),
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
77
|
+
router.post("/auth/login", (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("login")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "login"), ...[
|
|
78
|
+
safeCatchAsync(middlewares?.beforeLogin) || authController.login,
|
|
79
|
+
safeCatchAsync(middlewares?.beforeLogin)
|
|
80
|
+
? authController.login
|
|
81
|
+
: safeCatchAsync(middlewares?.afterLogin) || base_middlewares_1.sendResponse,
|
|
82
|
+
safeCatchAsync(middlewares?.beforeLogin) &&
|
|
83
|
+
safeCatchAsync(middlewares?.afterLogin)
|
|
84
|
+
? safeCatchAsync(middlewares?.afterLogin)
|
|
85
|
+
: base_middlewares_1.sendResponse,
|
|
86
|
+
base_middlewares_1.sendResponse,
|
|
87
|
+
].filter((middleware) => !!middleware));
|
|
88
|
+
router.delete("/auth/logout", auth_service_1.default.authenticate, ...[
|
|
89
|
+
safeCatchAsync(middlewares?.beforeLogout) || authController.logout,
|
|
90
|
+
safeCatchAsync(middlewares?.beforeLogout)
|
|
91
|
+
? authController.logout
|
|
92
|
+
: safeCatchAsync(middlewares?.afterLogout) || base_middlewares_1.sendResponse,
|
|
93
|
+
safeCatchAsync(middlewares?.beforeLogout) &&
|
|
94
|
+
safeCatchAsync(middlewares?.afterLogout)
|
|
95
|
+
? safeCatchAsync(middlewares?.afterLogout)
|
|
96
|
+
: base_middlewares_1.sendResponse,
|
|
97
|
+
base_middlewares_1.sendResponse,
|
|
98
|
+
].filter((middleware) => !!middleware));
|
|
99
|
+
router.post("/auth/signup", (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("signup")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "signup"), ...[
|
|
100
|
+
safeCatchAsync(middlewares?.beforeSignup) || authController.signup,
|
|
101
|
+
safeCatchAsync(middlewares?.beforeSignup)
|
|
102
|
+
? authController.signup
|
|
103
|
+
: safeCatchAsync(middlewares?.afterSignup) || base_middlewares_1.sendResponse,
|
|
104
|
+
safeCatchAsync(middlewares?.beforeSignup) &&
|
|
105
|
+
safeCatchAsync(middlewares?.afterSignup)
|
|
106
|
+
? safeCatchAsync(middlewares?.afterSignup)
|
|
107
|
+
: base_middlewares_1.sendResponse,
|
|
108
|
+
base_middlewares_1.sendResponse,
|
|
109
|
+
].filter((middleware) => !!middleware));
|
|
110
|
+
router.post("/auth/update-password", auth_service_1.default.authenticate, (0, base_middlewares_1.handleRequestBodyValidationAndTransformation)(getValidationSchemaOrDto("updatePassword")), (0, base_middlewares_1.addPrismaQueryOptionsToRequest)(prismaQueryOptions, "updatePassword"), ...[
|
|
111
|
+
safeCatchAsync(middlewares?.beforeUpdatePassword) ||
|
|
112
|
+
authController.updatePassword,
|
|
113
|
+
safeCatchAsync(middlewares?.beforeUpdatePassword)
|
|
114
|
+
? authController.updatePassword
|
|
115
|
+
: safeCatchAsync(middlewares?.afterUpdatePassword) || base_middlewares_1.sendResponse,
|
|
116
|
+
safeCatchAsync(middlewares?.beforeUpdatePassword) &&
|
|
117
|
+
safeCatchAsync(middlewares?.afterUpdatePassword)
|
|
118
|
+
? safeCatchAsync(middlewares?.afterUpdatePassword)
|
|
119
|
+
: base_middlewares_1.sendResponse,
|
|
120
|
+
base_middlewares_1.sendResponse,
|
|
121
|
+
].filter((middleware) => !!middleware));
|
|
75
122
|
return router;
|
|
76
123
|
}
|
|
77
124
|
//# sourceMappingURL=auth.router.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.router.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.router.ts"],"names":[],"mappings":";;;;;AAgBA,sCAiKC;AAjLD,qCAAiC;AACjC,uDAA0D;AAC1D,kEAAyC;AACzC,4EAA2C;AAC3C,uEAA8E;AAC9E,+DAIkC;AAElC,4FAA6D;AAG7D,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;AAEzB,KAAK,UAAU,aAAa,CAAC,YAAyB;IAC3D,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,kBAAkB,EAAE,GACtD,MAAM,IAAA,yCAAwB,EAAC,MAAM,CAAC,CAAC;IACzC,MAAM,cAAc,GAAG,MAAM,IAAA,uCAAqB,EAAC,WAAW,CAAC,CAAC;IAGhE,MAAM,wBAAwB,GAAG,CAAC,GAAW,EAAE,EAAE;QAC/C,MAAM,iBAAiB,GAAG,YAAY,EAAE,UAAU,CAAC;QACnD,IAAI,iBAAiB,EAAE,QAAQ,KAAK,iBAAiB,EAAE,CAAC;YACtD,OAAO,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC;aAAM,IAAI,iBAAiB,EAAE,QAAQ,KAAK,KAAK,EAAE,CAAC;YACjD,OAAO,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC;QACxB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;IAEF,MAAM;SACH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,EACd,IAAA,+DAA4C,EAC1C,wBAAwB,CAAC,QAAQ,CAAC,CACnC,EACD,IAAA,iDAA8B,EAC5B,kBAAiD,EACjD,QAAQ,CACT,EACD,WAAW,EAAE,YAAY,IAAI,cAAc,CAAC,MAAM,EAClD,WAAW,EAAE,YAAY;QACvB,CAAC,CAAC,cAAc,CAAC,MAAM;QACvB,CAAC,CAAC,WAAW,EAAE,WAAW,IAAI,+BAAY,EAC5C,WAAW,EAAE,YAAY,IAAI,WAAW,EAAE,WAAW;QACnD,CAAC,CAAC,WAAW,EAAE,WAAW;QAC1B,CAAC,CAAC,+BAAY,EAChB,+BAAY,CACb,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,uBAAuB,EACvB,sBAAW,CAAC,YAAY,EACxB,IAAA,+DAA4C,EAC1C,wBAAwB,CAAC,gBAAgB,CAAC,CAC3C,EACD,IAAA,iDAA8B,EAC5B,kBAAiD,EACjD,gBAAgB,CACjB,EACD,WAAW,EAAE,oBAAoB,IAAI,cAAc,CAAC,cAAc,EAClE,WAAW,EAAE,oBAAoB;QAC/B,CAAC,CAAC,cAAc,CAAC,cAAc;QAC/B,CAAC,CAAC,WAAW,EAAE,mBAAmB,IAAI,+BAAY,EACpD,WAAW,EAAE,oBAAoB,IAAI,WAAW,EAAE,mBAAmB;QACnE,CAAC,CAAC,WAAW,EAAE,mBAAmB;QAClC,CAAC,CAAC,+BAAY,EAChB,+BAAY,CACb,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { authControllerFactory } from \"./auth.controller\";\nimport authService from \"./auth.service\";\nimport rateLimit from \"express-rate-limit\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../base/base.middlewares\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthPrismaQueryOptions } from \"../../types\";\n\nconst router: Router = Router();\n\nexport async function getAuthRouter(arkosConfigs: ArkosConfig) {\n const { middlewares, dtos, schemas, prismaQueryOptions } =\n await importPrismaModelModules(\"auth\");\n const authController = await authControllerFactory(middlewares);\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (key: string) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n router\n .get(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"getMe\"\n ),\n middlewares?.beforeGetMe || authController.getMe,\n middlewares?.beforeGetMe\n ? authController.getMe\n : middlewares?.afterGetMe || sendResponse,\n middlewares?.beforeGetMe && middlewares?.afterGetMe\n ? middlewares?.afterGetMe\n : sendResponse,\n sendResponse\n )\n .patch(\n \"/users/me\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMe\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updateMe\"\n ),\n middlewares?.beforeUpdateMe || authController.updateMe,\n middlewares?.beforeUpdateMe\n ? authController.updateMe\n : middlewares?.afterUpdateMe || sendResponse,\n middlewares?.beforeUpdateMe && middlewares?.afterUpdateMe\n ? middlewares?.afterUpdateMe\n : sendResponse,\n sendResponse\n )\n .delete(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"deleteMe\"\n ),\n middlewares?.beforeDeleteMe || authController.deleteMe,\n middlewares?.beforeDeleteMe\n ? authController.deleteMe\n : middlewares?.afterDeleteMe || sendResponse,\n middlewares?.beforeDeleteMe && middlewares?.afterDeleteMe\n ? middlewares?.afterDeleteMe\n : sendResponse,\n sendResponse\n );\n\n router.use(\n \"/auth\",\n rateLimit(\n deepmerge(\n {\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (req, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfigs?.authentication?.requestRateLimitOptions || {}\n )\n )\n );\n\n router.post(\n \"/auth/login\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"login\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"login\"\n ),\n middlewares?.beforeLogin || authController.login,\n middlewares?.beforeLogin\n ? authController.login\n : middlewares?.afterLogin || sendResponse,\n middlewares?.beforeLogin && middlewares?.afterLogin\n ? middlewares?.afterLogin\n : sendResponse,\n sendResponse\n );\n\n router.delete(\n \"/auth/logout\",\n authService.authenticate,\n middlewares?.beforeLogout || authController.logout,\n middlewares?.beforeLogout\n ? authController.logout\n : middlewares?.afterLogout || sendResponse,\n middlewares?.beforeLogout && middlewares?.afterLogout\n ? middlewares?.afterLogout\n : sendResponse,\n sendResponse\n );\n\n router.post(\n \"/auth/signup\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"signup\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"signup\"\n ),\n middlewares?.beforeSignup || authController.signup,\n middlewares?.beforeSignup\n ? authController.signup\n : middlewares?.afterSignup || sendResponse,\n middlewares?.beforeSignup && middlewares?.afterSignup\n ? middlewares?.afterSignup\n : sendResponse,\n sendResponse\n );\n\n router.post(\n \"/auth/update-password\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updatePassword\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updatePassword\"\n ),\n middlewares?.beforeUpdatePassword || authController.updatePassword,\n middlewares?.beforeUpdatePassword\n ? authController.updatePassword\n : middlewares?.afterUpdatePassword || sendResponse,\n middlewares?.beforeUpdatePassword && middlewares?.afterUpdatePassword\n ? middlewares?.afterUpdatePassword\n : sendResponse,\n sendResponse\n );\n\n return router;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auth.router.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.router.ts"],"names":[],"mappings":";;;;;AAiBA,sCA4LC;AA7MD,qCAAiC;AACjC,uDAA0D;AAC1D,kEAAyC;AACzC,4EAA2C;AAC3C,uEAA8E;AAC9E,+DAIkC;AAElC,4FAA6D;AAE7D,qFAA4D;AAE5D,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;AAEzB,KAAK,UAAU,aAAa,CAAC,YAAyB;IAC3D,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,kBAAkB,EAAE,GACtD,MAAM,IAAA,yCAAwB,EAAC,MAAM,CAAC,CAAC;IACzC,MAAM,cAAc,GAAG,MAAM,IAAA,uCAAqB,EAAC,WAAW,CAAC,CAAC;IAGhE,MAAM,wBAAwB,GAAG,CAAC,GAAW,EAAE,EAAE;QAC/C,MAAM,iBAAiB,GAAG,YAAY,EAAE,UAAU,CAAC;QACnD,IAAI,iBAAiB,EAAE,QAAQ,KAAK,iBAAiB,EAAE,CAAC;YACtD,OAAO,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC;aAAM,IAAI,iBAAiB,EAAE,QAAQ,KAAK,KAAK,EAAE,CAAC;YACjD,OAAO,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC;QACxB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;IAGF,MAAM,cAAc,GAAG,CAAC,UAAe,EAAE,EAAE;QACzC,OAAO,UAAU,CAAC,CAAC,CAAC,IAAA,qBAAU,EAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACzD,CAAC,CAAC;IAEF,MAAM;S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AC,CAAC,cAAc,CAAC,MAAM;YACvB,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC,IAAI,+BAAY;QAC5D,cAAc,CAAC,WAAW,EAAE,YAAY,CAAC;YACzC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC;YACtC,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,WAAW,CAAC;YAC1C,CAAC,CAAC,+BAAY;QAChB,+BAAY;KACb,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CACvC,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,uBAAuB,EACvB,sBAAW,CAAC,YAAY,EACxB,IAAA,+DAA4C,EAC1C,wBAAwB,CAAC,gBAAgB,CAAC,CAC3C,EACD,IAAA,iDAA8B,EAC5B,kBAAiD,EACjD,gBAAgB,CACjB,EACD,GAAG;QACD,cAAc,CAAC,WAAW,EAAE,oBAAoB,CAAC;YAC/C,cAAc,CAAC,cAAc;QAC/B,cAAc,CAAC,WAAW,EAAE,oBAAoB,CAAC;YAC/C,CAAC,CAAC,cAAc,CAAC,cAAc;YAC/B,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,mBAAmB,CAAC,IAAI,+BAAY;QACpE,cAAc,CAAC,WAAW,EAAE,oBAAoB,CAAC;YACjD,cAAc,CAAC,WAAW,EAAE,mBAAmB,CAAC;YAC9C,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,mBAAmB,CAAC;YAClD,CAAC,CAAC,+BAAY;QAChB,+BAAY;KACb,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CACvC,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { authControllerFactory } from \"./auth.controller\";\nimport authService from \"./auth.service\";\nimport rateLimit from \"express-rate-limit\";\nimport { importPrismaModelModules } from \"../../utils/helpers/models.helpers\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../base/base.middlewares\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthPrismaQueryOptions } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\n\nconst router: Router = Router();\n\nexport async function getAuthRouter(arkosConfigs: ArkosConfig) {\n const { middlewares, dtos, schemas, prismaQueryOptions } =\n await importPrismaModelModules(\"auth\");\n const authController = await authControllerFactory(middlewares);\n\n // Helper to get the correct schema or DTO based on Arkos Config\n const getValidationSchemaOrDto = (key: string) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n // Helper to conditionally wrap middleware with catchAsync\n const safeCatchAsync = (middleware: any) => {\n return middleware ? catchAsync(middleware) : undefined;\n };\n\n router\n .get(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"getMe\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeGetMe) || authController.getMe,\n safeCatchAsync(middlewares?.beforeGetMe)\n ? authController.getMe\n : safeCatchAsync(middlewares?.afterGetMe) || sendResponse,\n safeCatchAsync(middlewares?.beforeGetMe) &&\n safeCatchAsync(middlewares?.afterGetMe)\n ? safeCatchAsync(middlewares?.afterGetMe)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n )\n .patch(\n \"/users/me\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updateMe\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updateMe\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdateMe) || authController.updateMe,\n safeCatchAsync(middlewares?.beforeUpdateMe)\n ? authController.updateMe\n : safeCatchAsync(middlewares?.afterUpdateMe) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdateMe) &&\n safeCatchAsync(middlewares?.afterUpdateMe)\n ? safeCatchAsync(middlewares?.afterUpdateMe)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n )\n .delete(\n \"/users/me\",\n authService.authenticate,\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"deleteMe\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeDeleteMe) || authController.deleteMe,\n safeCatchAsync(middlewares?.beforeDeleteMe)\n ? authController.deleteMe\n : safeCatchAsync(middlewares?.afterDeleteMe) || sendResponse,\n safeCatchAsync(middlewares?.beforeDeleteMe) &&\n safeCatchAsync(middlewares?.afterDeleteMe)\n ? safeCatchAsync(middlewares?.afterDeleteMe)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.use(\n \"/auth\",\n rateLimit(\n deepmerge(\n {\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (req, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfigs?.authentication?.requestRateLimitOptions || {}\n )\n )\n );\n\n router.post(\n \"/auth/login\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"login\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"login\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeLogin) || authController.login,\n safeCatchAsync(middlewares?.beforeLogin)\n ? authController.login\n : safeCatchAsync(middlewares?.afterLogin) || sendResponse,\n safeCatchAsync(middlewares?.beforeLogin) &&\n safeCatchAsync(middlewares?.afterLogin)\n ? safeCatchAsync(middlewares?.afterLogin)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.delete(\n \"/auth/logout\",\n authService.authenticate,\n ...[\n safeCatchAsync(middlewares?.beforeLogout) || authController.logout,\n safeCatchAsync(middlewares?.beforeLogout)\n ? authController.logout\n : safeCatchAsync(middlewares?.afterLogout) || sendResponse,\n safeCatchAsync(middlewares?.beforeLogout) &&\n safeCatchAsync(middlewares?.afterLogout)\n ? safeCatchAsync(middlewares?.afterLogout)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.post(\n \"/auth/signup\",\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"signup\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"signup\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeSignup) || authController.signup,\n safeCatchAsync(middlewares?.beforeSignup)\n ? authController.signup\n : safeCatchAsync(middlewares?.afterSignup) || sendResponse,\n safeCatchAsync(middlewares?.beforeSignup) &&\n safeCatchAsync(middlewares?.afterSignup)\n ? safeCatchAsync(middlewares?.afterSignup)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n router.post(\n \"/auth/update-password\",\n authService.authenticate,\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"updatePassword\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updatePassword\"\n ),\n ...[\n safeCatchAsync(middlewares?.beforeUpdatePassword) ||\n authController.updatePassword,\n safeCatchAsync(middlewares?.beforeUpdatePassword)\n ? authController.updatePassword\n : safeCatchAsync(middlewares?.afterUpdatePassword) || sendResponse,\n safeCatchAsync(middlewares?.beforeUpdatePassword) &&\n safeCatchAsync(middlewares?.afterUpdatePassword)\n ? safeCatchAsync(middlewares?.afterUpdatePassword)\n : sendResponse,\n sendResponse,\n ].filter((middleware) => !!middleware)\n );\n\n return router;\n}\n"]}
|
|
@@ -14,6 +14,7 @@ const deepmerge_helper_1 = __importDefault(require("../../utils/helpers/deepmerg
|
|
|
14
14
|
const error_handler_1 = require("../../exports/error-handler");
|
|
15
15
|
const validate_dto_1 = __importDefault(require("../../utils/validate-dto"));
|
|
16
16
|
const validate_schema_1 = __importDefault(require("../../utils/validate-schema"));
|
|
17
|
+
const base_middlewares_helpers_1 = require("./utils/helpers/base.middlewares.helpers");
|
|
17
18
|
function callNext(req, res, next) {
|
|
18
19
|
next();
|
|
19
20
|
}
|
|
@@ -33,17 +34,12 @@ function addRouteMiddlwaresAndConfigs() { }
|
|
|
33
34
|
function addPrismaQueryOptionsToRequest(prismaQueryOptions, action) {
|
|
34
35
|
return (req, res, next) => {
|
|
35
36
|
const configs = (0, server_1.getArkosConfig)();
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
else {
|
|
43
|
-
req.prismaQueryOptions = (0, deepmerge_helper_1.default)(prismaQueryOptions?.queryOptions || {}, JSON.parse(configs?.request?.parameters?.allowDangerousPrismaQueryOptions
|
|
44
|
-
? req.query?.prismaQueryOptions || "{}"
|
|
45
|
-
: "{}"));
|
|
46
|
-
}
|
|
37
|
+
const resolvedOptions = (0, base_middlewares_helpers_1.resolvePrismaQueryOptions)(prismaQueryOptions, action);
|
|
38
|
+
const requestQueryOptions = configs?.request?.parameters
|
|
39
|
+
?.allowDangerousPrismaQueryOptions
|
|
40
|
+
? JSON.parse(req.query?.prismaQueryOptions || "{}")
|
|
41
|
+
: {};
|
|
42
|
+
req.prismaQueryOptions = (0, deepmerge_helper_1.default)(resolvedOptions, requestQueryOptions);
|
|
47
43
|
next();
|
|
48
44
|
};
|
|
49
45
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.middlewares.js","sourceRoot":"","sources":["../../../../src/modules/base/base.middlewares.ts"],"names":[],"mappings":";;;;;AAkBA,4BAEC;AAED,oCAeC;AAED,oEAAiD;AAkBjD,wEAoCC;AAKD,8CAuDC;AAcD,oGA2B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G,CAAC,IAAI,CAAC;QAEpB,IAAI,iBAAiB,EAAE,QAAQ,KAAK,iBAAiB,IAAI,gBAAgB;YACvE,GAAG,CAAC,IAAI,GAAG,MAAM,IAAA,sBAAW,EAC1B,gBAAuC,EACvC,IAAI,EACJ,IAAA,0BAAS,EACP;gBACE,SAAS,EAAE,IAAI;gBACf,GAAG,+BAA+B;aACnC,EACD,iBAAiB,EAAE,iBAAiB,IAAI,EAAE,CAC3C,CACF,CAAC;aACC,IAAI,iBAAiB,EAAE,QAAQ,KAAK,KAAK,IAAI,gBAAgB;YAChE,GAAG,CAAC,IAAI,GAAG,MAAM,IAAA,yBAAc,EAAC,gBAAgC,EAAE,IAAI,CAAC,CAAC;QAE1E,IAAI,EAAE,CAAC;IACT,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport {\n PrismaQueryOptions,\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n AuthPrismaQueryOptions,\n} from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport validateDto from \"../../utils/validate-dto\";\nimport validateSchema from \"../../utils/validate-schema\";\nimport { ZodSchema } from \"zod\";\nimport { ClassConstructor } from \"class-transformer\";\nimport { ValidatorOptions } from \"class-validator\";\n\nexport function callNext(req: Request, res: Response, next: NextFunction) {\n next();\n}\n\nexport function sendResponse(\n req: ArkosRequest,\n res: ArkosResponse,\n next: NextFunction\n) {\n if (Number(req?.responseStatus) === 204)\n res.status(Number(req?.responseStatus)).send();\n else if (req.responseData && req?.responseStatus)\n res.status(Number(req?.responseStatus)).json(req.responseData);\n else if (Number(req?.responseStatus) && !req.responseData)\n res.status(Number(req?.responseStatus)).send();\n else\n res\n .status(500)\n .json({ message: \"No status or data attached to the response\" });\n}\n\nexport function addRouteMiddlwaresAndConfigs() {}\n\n/**\n * Type representing all possible actions that can be performed on a controller\n * Combines both standard CRUD operations and auth-specific operations\n */\nexport type ControllerActions =\n | keyof PrismaQueryOptions<any>\n | keyof Omit<AuthPrismaQueryOptions<any>, keyof PrismaQueryOptions<any>>;\n\n/**\n * Middleware to add Prisma query options to the request's query parameters.\n *\n * @template T - The type of the Prisma model.\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options to attach.\n * @param {ControllerActions} action - The controller action to apply.\n * @returns A middleware function that attaches the query options to the request.\n */\nexport function addPrismaQueryOptionsToRequest<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n) {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const configs = getArkosConfig();\n\n // Check if the action exists in the provided options object\n if (prismaQueryOptions && action in prismaQueryOptions) {\n const firstMerge = deepmerge(\n (prismaQueryOptions as any)?.queryOptions || {},\n (prismaQueryOptions as any)[action] || {}\n ) as Record<string, any>;\n\n req.prismaQueryOptions = deepmerge(\n firstMerge,\n JSON.parse(\n configs?.request?.parameters?.allowDangerousPrismaQueryOptions\n ? (req.query?.prismaQueryOptions as string) || \"{}\"\n : \"{}\"\n )\n );\n } else {\n // If no specific options for this action, just use the general queryOptions\n req.prismaQueryOptions = deepmerge(\n (prismaQueryOptions as any)?.queryOptions || {},\n JSON.parse(\n configs?.request?.parameters?.allowDangerousPrismaQueryOptions\n ? (req.query?.prismaQueryOptions as string) || \"{}\"\n : \"{}\"\n )\n );\n }\n\n next();\n };\n}\n/**\n * Logs request events with colored text such as errors, requests responses.\n *\n */\nexport function handleRequestLogs(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const startTime = Date.now(); // Capture the start time\n\n // Define colors for each HTTP method\n const methodColors = {\n GET: \"\\x1b[36m\", // Cyan\n POST: \"\\x1b[32m\", // Green\n PUT: \"\\x1b[33m\", // Orange/Yellow\n PATCH: \"\\x1b[33m\", // Orange/Yellow\n DELETE: \"\\x1b[31m\", // Red\n HEAD: \"\\x1b[34m\", // Blue\n OPTIONS: \"\\x1b[34m\", // Blue\n };\n\n // Function to determine status code color\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\"; // Green\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\"; // Orange/Yellow\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\"; // Red\n if (statusCode >= 500) return \"\\x1b[31m\"; // White on Red background\n return \"\\x1b[0m\"; // Default (no color)\n };\n\n res.on(\"finish\", () => {\n const duration = Date.now() - startTime; // Calculate the time taken to process the request\n\n // Get the current date and time\n const now = new Date();\n const dayNames = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n const dayName = dayNames[now.getDay()];\n const dayOfMonth = now.getDate();\n const time = now.toTimeString().split(\" \")[0]; // Format as HH:MM:SS\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\"; // Default to no color\n const statusColor = getStatusColor(res.statusCode); // Get the color for the status code\n\n console.info(\n `[\\x1b[36mINFO\\x1b[0m] \\x1b[90m${time}\\x1b[0m ${methodColor}${\n req.method\n }\\x1b[0m ${decodeURIComponent(req.originalUrl)} ${statusColor}${\n res.statusCode\n }\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n );\n // Keep the commented-out example as it is\n // console.info(\n // `[\\x1b[36mINFO\\x1b[0m] ${dayName} ${dayOfMonth} ${time} ${methodColor}${req.method}\\x1b[0m ${req.originalUrl} \\x1b[32m${res.statusCode}\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n // );\n });\n\n next(); // Pass control to the next middleware or route handler\n}\n\n// Overload for 'auth'\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n): ArkosRequestHandler;\n\n// Overload for other models\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T>\n): ArkosRequestHandler;\n\n// Implementation\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T> | ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n) {\n return catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (validationConfigs?.resolver === \"class-validator\" && schemaOrDtoClass)\n req.body = await validateDto(\n schemaOrDtoClass as ClassConstructor<T>,\n body,\n deepmerge(\n {\n whitelist: true,\n ...classValidatorValidationOptions,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (validationConfigs?.resolver === \"zod\" && schemaOrDtoClass)\n req.body = await validateSchema(schemaOrDtoClass as ZodSchema<T>, body);\n\n next();\n }\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.middlewares.js","sourceRoot":"","sources":["../../../../src/modules/base/base.middlewares.ts"],"names":[],"mappings":";;;;;AAmBA,4BAEC;AAED,oCAeC;AAED,oEAAiD;AAkBjD,wEAwBC;AAMD,8CAuDC;AAcD,oGA2BC;AA/KD,yCAA8C;AAC9C,4FAA6D;AAC7D,+DAAyD;AACzD,4EAAmD;AACnD,kFAAyD;AAIzD,uFAAqF;AAErF,SAAgB,QAAQ,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;IACtE,IAAI,EAAE,CAAC;AACT,CAAC;AAED,SAAgB,YAAY,CAC1B,GAAiB,EACjB,GAAkB,EAClB,IAAuB;IAEvB,IAAI,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,KAAK,GAAG;QACrC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;SAC5C,IAAI,GAAG,CAAC,YAAY,IAAI,GAAG,EAAE,cAAc;QAC9C,GAAG,CAAC,MAAM,CAAC,MAAM,CA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AG,CAAC,WAAW,CAAC,IAAI,WAAW,GAC3D,GAAG,CAAC,UACN,mBAAmB,QAAQ,WAAW,CACvC,CAAC;IAKJ,CAAC,CAAC,CAAC;IAEH,IAAI,EAAE,CAAC;AACT,CAAC;AAcD,SAAgB,4CAA4C,CAC1D,gBAAqD,EACrD,+BAAkD;IAElD,OAAO,IAAA,0BAAU,EACf,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;QACvE,MAAM,iBAAiB,GAAG,IAAA,uBAAc,GAAE,EAAE,UAAU,CAAC;QACvD,IAAI,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;QAEpB,IAAI,iBAAiB,EAAE,QAAQ,KAAK,iBAAiB,IAAI,gBAAgB;YACvE,GAAG,CAAC,IAAI,GAAG,MAAM,IAAA,sBAAW,EAC1B,gBAAuC,EACvC,IAAI,EACJ,IAAA,0BAAS,EACP;gBACE,SAAS,EAAE,IAAI;gBACf,GAAG,+BAA+B;aACnC,EACD,iBAAiB,EAAE,iBAAiB,IAAI,EAAE,CAC3C,CACF,CAAC;aACC,IAAI,iBAAiB,EAAE,QAAQ,KAAK,KAAK,IAAI,gBAAgB;YAChE,GAAG,CAAC,IAAI,GAAG,MAAM,IAAA,yBAAc,EAAC,gBAAgC,EAAE,IAAI,CAAC,CAAC;QAE1E,IAAI,EAAE,CAAC;IACT,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport {\n PrismaQueryOptions,\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n AuthPrismaQueryOptions,\n} from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport validateDto from \"../../utils/validate-dto\";\nimport validateSchema from \"../../utils/validate-schema\";\nimport { ZodSchema } from \"zod\";\nimport { ClassConstructor } from \"class-transformer\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { resolvePrismaQueryOptions } from \"./utils/helpers/base.middlewares.helpers\";\n\nexport function callNext(req: Request, res: Response, next: NextFunction) {\n next();\n}\n\nexport function sendResponse(\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n) {\n if (Number(req?.responseStatus) === 204)\n res.status(Number(req?.responseStatus)).send();\n else if (req.responseData && req?.responseStatus)\n res.status(Number(req?.responseStatus)).json(req.responseData);\n else if (Number(req?.responseStatus) && !req.responseData)\n res.status(Number(req?.responseStatus)).send();\n else\n res\n .status(500)\n .json({ message: \"No status or data attached to the response\" });\n}\n\nexport function addRouteMiddlwaresAndConfigs() {}\n\n/**\n * Type representing all possible actions that can be performed on a controller\n * Combines both standard CRUD operations and auth-specific operations\n */\nexport type ControllerActions =\n | keyof PrismaQueryOptions<any>\n | keyof Omit<AuthPrismaQueryOptions<any>, keyof PrismaQueryOptions<any>>;\n\n/**\n * Middleware to add Prisma query options to the request's query parameters.\n *\n * @template T - The type of the Prisma model.\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options to attach.\n * @param {ControllerActions} action - The controller action to apply.\n * @returns A middleware function that attaches the query options to the request.\n */\nexport function addPrismaQueryOptionsToRequest<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n) {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const configs = getArkosConfig();\n\n // Resolve and merge all applicable options using the helper\n const resolvedOptions = resolvePrismaQueryOptions(\n prismaQueryOptions,\n action\n );\n\n // Parse and merge any dangerous query options from request if allowed\n const requestQueryOptions = configs?.request?.parameters\n ?.allowDangerousPrismaQueryOptions\n ? JSON.parse((req.query?.prismaQueryOptions as string) || \"{}\")\n : {};\n\n // Final merge with request options having the highest priority\n req.prismaQueryOptions = deepmerge(resolvedOptions, requestQueryOptions);\n\n next();\n };\n}\n\n/**\n * Logs request events with colored text such as errors, requests responses.\n *\n */\nexport function handleRequestLogs(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const startTime = Date.now(); // Capture the start time\n\n // Define colors for each HTTP method\n const methodColors = {\n GET: \"\\x1b[36m\", // Cyan\n POST: \"\\x1b[32m\", // Green\n PUT: \"\\x1b[33m\", // Orange/Yellow\n PATCH: \"\\x1b[33m\", // Orange/Yellow\n DELETE: \"\\x1b[31m\", // Red\n HEAD: \"\\x1b[34m\", // Blue\n OPTIONS: \"\\x1b[34m\", // Blue\n };\n\n // Function to determine status code color\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\"; // Green\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\"; // Orange/Yellow\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\"; // Red\n if (statusCode >= 500) return \"\\x1b[31m\"; // White on Red background\n return \"\\x1b[0m\"; // Default (no color)\n };\n\n res.on(\"finish\", () => {\n const duration = Date.now() - startTime; // Calculate the time taken to process the request\n\n // Get the current date and time\n const now = new Date();\n const dayNames = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n const dayName = dayNames[now.getDay()];\n const dayOfMonth = now.getDate();\n const time = now.toTimeString().split(\" \")[0]; // Format as HH:MM:SS\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\"; // Default to no color\n const statusColor = getStatusColor(res.statusCode); // Get the color for the status code\n\n console.info(\n `[\\x1b[36mINFO\\x1b[0m] \\x1b[90m${time}\\x1b[0m ${methodColor}${\n req.method\n }\\x1b[0m ${decodeURIComponent(req.originalUrl)} ${statusColor}${\n res.statusCode\n }\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n );\n // Keep the commented-out example as it is\n // console.info(\n // `[\\x1b[36mINFO\\x1b[0m] ${dayName} ${dayOfMonth} ${time} ${methodColor}${req.method}\\x1b[0m ${req.originalUrl} \\x1b[32m${res.statusCode}\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n // );\n });\n\n next(); // Pass control to the next middleware or route handler\n}\n\n// Overload for 'auth'\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n): ArkosRequestHandler;\n\n// Overload for other models\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T>\n): ArkosRequestHandler;\n\n// Implementation\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T> | ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n) {\n return catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (validationConfigs?.resolver === \"class-validator\" && schemaOrDtoClass)\n req.body = await validateDto(\n schemaOrDtoClass as ClassConstructor<T>,\n body,\n deepmerge(\n {\n whitelist: true,\n ...classValidatorValidationOptions,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (validationConfigs?.resolver === \"zod\" && schemaOrDtoClass)\n req.body = await validateSchema(schemaOrDtoClass as ZodSchema<T>, body);\n\n next();\n }\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":";;;;;;AAidA,0CAOC;AAxdD,iFAIiD;AACjD,uEAI4C;AAC5C,4FAA6D;AAC7D,+EAAkF;AAClF,uEAAuE;AACvE,wEAA+C;AAuB/C,MAAa,WAAW;IAuBtB,YAAY,SAAiB;QAC3B,IAAI,CAAC,SAAS,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,cAAc,GAAG,IAAA,wCAAuB,EAAC,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAE,CAAC;IACxE,CAAC;I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D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,IAAA,+BAAS,EAAC,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport {\n getModels,\n getPrismaModelRelations,\n RelationFields,\n} from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { handleRelationFieldsInBody } from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n *\n * by model-specific service classes.\n *\n * @class BaseService\n *\n * @usage\n *\n * **Example:** creating a simple service\n *\n * ```ts\n * import { prisma } from '../../utils/prisma'\n *\n * const userService = new BaseService<typeof prisma.user>(\"user\")\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-service-class}\n *\n */\nexport class BaseService<ModelDelegate extends Record<string, any> = any> {\n /**\n * The camelCase name of the model\n * @public\n */\n modelName: string;\n\n /**\n * Object containing singular and list relation fields for the model\n * @public\n */\n relationFields: RelationFields;\n\n /**\n * Instance of the Prisma client\n * @public\n */\n prisma: any;\n\n /**\n * Creates an instance of BaseService.\n * @param {string} modelName - The name of the model to perform operations on.\n */\n constructor(modelName: string) {\n this.modelName = camelCase(modelName);\n this.relationFields = getPrismaModelRelations(pascalCase(modelName))!;\n }\n\n /**\n * Creates a single record in the database.\n *\n * @param {Parameters<ModelDelegate[\"create\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to create the record with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"create\"]>>} The created record.\n */\n async createOne<\n TOptions extends Omit<Parameters<ModelDelegate[\"create\"]>[0], \"data\">,\n >(\n data: Parameters<ModelDelegate[\"create\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"create\"] extends (args: { data: any }) => infer R ? R : any\n > {\n // user uer Password123 true false Promise { true }\n if (kebabCase(this.modelName) === \"user\" && (data as any).password)\n if (!authService.isPasswordHashed((data as any).password))\n (data as any).password = await authService.hashPassword(\n (data as any).password\n );\n\n const prisma = getPrismaInstance();\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(\n data as Record<string, any>,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n return await (prisma[this.modelName] as ModelDelegate).create(\n deepmerge(\n {\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { data: any }\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Parameters<ModelDelegate[\"createMany\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - An array of data to create records with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"createMany\"]>>} The result of the createMany operation.\n */\n async createMany<\n TOptions extends Omit<Parameters<ModelDelegate[\"createMany\"]>[0], \"data\">,\n >(\n data: Parameters<ModelDelegate[\"createMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"createMany\"] extends (args: { data: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (Array.isArray(data))\n (data as { [x: string]: any; password?: string }[]).forEach(\n async (curr, i) => {\n if (\"password\" in curr && this.modelName === \"user\")\n if (!authService.isPasswordHashed(curr.password!))\n curr.password = await authService.hashPassword(curr?.password!);\n\n data[i] = handleRelationFieldsInBody(\n data[i] as Record<string, any>,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).createMany(\n deepmerge({ data }, (queryOptions as {}) || {}) as {\n data: any;\n }\n );\n }\n\n /**\n * Counts records based on provided filters.\n *\n * @param {Parameters<ModelDelegate[\"count\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to apply to the query.\n * @returns {Promise<number>} The count of records matching the filters.\n */\n async count(\n filters: Parameters<ModelDelegate[\"count\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<number> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).count({\n where: filters,\n });\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Parameters<ModelDelegate[\"findMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to apply to the query.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findMany\"]>>} The found data.\n */\n async findMany<\n TOptions extends Omit<Parameters<ModelDelegate[\"findMany\"]>[0], \"where\">,\n >(\n filters: Parameters<ModelDelegate[\"findMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n Awaited<\n ReturnType<\n ModelDelegate[\"findMany\"] extends (\n args: { where: any } & TOptions\n ) => any\n ? ModelDelegate[\"findMany\"]\n : never\n >\n >\n > {\n const prisma = getPrismaInstance();\n return await (prisma[this.modelName] as ModelDelegate).findMany(\n deepmerge({ where: filters }, queryOptions || {})\n );\n }\n\n /**\n * Finds a single record by its ID.\n *\n * @param {string | number} id - The ID of the record to find.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findUnique\"]>>} The found record or null if not found.\n */\n async findById<\n TOptions extends Omit<Parameters<ModelDelegate[\"findUnique\"]>[0], \"where\">,\n >(\n id: string | number,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findUnique\"] extends (args: { where: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).findUnique(\n deepmerge(\n {\n where: { id },\n },\n queryOptions || {}\n ) as { where: { id: string | number } }\n );\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Parameters<ModelDelegate[\"findFirst\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any | Parameters<TModel[\"findUnique\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findOne<\n TOptions extends\n | Omit<Parameters<ModelDelegate[\"findFirst\"]>[0], \"where\">\n | Omit<Parameters<ModelDelegate[\"findUnique\"]>[0], \"where\">,\n >(\n filters: Parameters<ModelDelegate[\"findFirst\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any | Parameters<ModelDelegate[\"findUnique\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findFirst\"] extends (args: { where: any }) => infer R\n ? R\n : ModelDelegate[\"findUnique\"] extends (args: { where: any }) => infer R2\n ? R2\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (\n Object.keys(filters as Record<string, any>).length === 1 &&\n \"id\" in (filters as Record<string, any>) &&\n (filters as any).id !== \"me\"\n )\n return (prisma[this.modelName] as ModelDelegate).findUnique(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).findFirst(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any }\n );\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Parameters<ModelDelegate[\"update\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {Parameters<ModelDelegate[\"update\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to update the record with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"update\"]>>} The updated record or null if not found.\n */\n async updateOne<\n TOptions extends Omit<\n Parameters<ModelDelegate[\"update\"]>[0],\n \"where\" | \"data\"\n >,\n >(\n filters: Parameters<ModelDelegate[\"update\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<ModelDelegate[\"update\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"update\"] extends (args: { where: any; data: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && (data as any)?.password) {\n if (!authService.isPasswordHashed((data as any).password!))\n (data as any).password = await authService.hashPassword(\n (data as any)?.password\n );\n }\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(\n data as Record<string, any>,\n {\n ...this.relationFields,\n }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).update(\n deepmerge(\n {\n where: filters,\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { where: any; data: any }\n );\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Parameters<ModelDelegate[\"updateMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to identify records to update.\n * @param {Parameters<ModelDelegate[\"updateMany\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to update the records with.\n * @param {TOptions} [queryOptions] - Additional query options.\n * @returns {Promise<ReturnType<ModelDelegate[\"updateMany\"]>>} The result of the updateMany operation.\n */\n async updateMany<\n TOptions extends Omit<\n Parameters<ModelDelegate[\"updateMany\"]>[0],\n \"where\" | \"data\"\n >,\n >(\n filters: Parameters<ModelDelegate[\"updateMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<ModelDelegate[\"updateMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"updateMany\"] extends (args: {\n where: any;\n data: any;\n }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (Array.isArray(data) && this.modelName === \"user\")\n (data as { [x: string]: any; password?: string }[]).forEach(\n async (curr, i) => {\n if (\"password\" in data[i])\n if (!authService.isPasswordHashed(curr.password!))\n (data[i] as any).password = await authService.hashPassword(\n curr.password!\n );\n }\n );\n\n const firstMerge = deepmerge({ data }, (queryOptions as {}) || {});\n\n return await (prisma[this.modelName] as ModelDelegate).updateMany(\n deepmerge({ where: filters }, firstMerge) as {\n where: any;\n data: any;\n }\n );\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Parameters<ModelDelegate[\"delete\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @returns {Promise<ReturnType<ModelDelegate[\"delete\"]>>} The deleted record or null if an error occurs.\n */\n async deleteOne(\n filters: Parameters<ModelDelegate[\"delete\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<ReturnType<ModelDelegate[\"delete\"]>> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).delete({\n where: filters,\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Parameters<ModelDelegate[\"deleteMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : Record<string, any>} filters - The filter to identify records to delete.\n * @returns {Promise<ReturnType<ModelDelegate[\"deleteMany\"]>>} The result of the deleteMany operation.\n */\n async deleteMany(\n filters: Parameters<ModelDelegate[\"deleteMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : Record<string, any>\n ): Promise<ReturnType<ModelDelegate[\"deleteMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).deleteMany({\n where: filters,\n });\n }\n}\n\n/**\n * Generates a set of base service instances for all available models.\n *\n * @returns {Record<string, BaseService>} A dictionary of base service instances, keyed by model name.\n */\nexport function getBaseServices(): Record<string, BaseService<any>> {\n const models = getModels();\n const baseServices: Record<string, BaseService<any>> = {};\n models.forEach((model) => {\n baseServices[`${camelCase(model)}`] = new BaseService(model);\n });\n return baseServices;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.js","sourceRoot":"","sources":["../../../../src/modules/base/base.service.ts"],"names":[],"mappings":";;;;;;AAgdA,0CAOC;AAvdD,iFAIiD;AACjD,uEAI4C;AAC5C,4FAA6D;AAC7D,+EAAkF;AAClF,uEAAuE;AACvE,wEAA+C;AAuB/C,MAAa,WAAW;IAuBtB,YAAY,SAAiB;QAC3B,IAAI,CAAC,SAAS,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC;QACtC,IAAI,CAAC,cAAc,GAAG,IAAA,wCAAuB,EAAC,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAE,CAAC;IACxE,CAAC;IASD,KAAK,CAAC,SAAS,CAGb,IAKO,EACP,YAAuB;QAKvB,IAAI,IAAA,+BAAS,EAAC,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAK,IAAY,CAAC,QAAQ;YAChE,IAAI,CAAC,sBAAW,CAAC,gBAAgB,CAAE,IAAY,CAAC,QAAQ,CAAC;gBACtD,IAAY,CAAC,QAAQ,GAAG,MAAM,sBAAW,CAAC,YAAY,CACpD,IAAY,CAAC,QAAQ,CACvB,CAAC;QAEN,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;QAEnC,MAAM,6BAA6B,GAAG,IAAA,iDAA0B,EAC9D,IAA2B,EAC3B;YACE,GAAG,IAAI,CAAC,cAA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AAC,EAAE,IAAI,EAAE,EAAG,YAAmB,IAAI,EAAE,CAAC,CAAC;QAEnE,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,UAAU,CAC/D,IAAA,0BAAS,EAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,UAAU,CAGvC,CACF,CAAC;IACJ,CAAC;IAQD,KAAK,CAAC,SAAS,CACb,OAKO;QAEP,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;QAEnC,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,MAAM,CAAC;YAC5D,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC;IAQD,KAAK,CAAC,UAAU,CACd,OAKuB;QAEvB,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;QAEnC,OAAO,MAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAmB,CAAC,UAAU,CAAC;YAChE,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;IACL,CAAC;CACF;AAraD,kCAqaC;AAOD,SAAgB,eAAe;IAC7B,MAAM,MAAM,GAAG,IAAA,0BAAS,GAAE,CAAC;IAC3B,MAAM,YAAY,GAAqC,EAAE,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;QACvB,YAAY,CAAC,GAAG,IAAA,+BAAS,EAAC,KAAK,CAAC,EAAE,CAAC,GAAG,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import {\n camelCase,\n kebabCase,\n pascalCase,\n} from \"../../utils/helpers/change-case.helpers\";\nimport {\n getModels,\n getPrismaModelRelations,\n RelationFields,\n} from \"../../utils/helpers/models.helpers\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { handleRelationFieldsInBody } from \"./utils/helpers/base.service.helpers\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport authService from \"../auth/auth.service\";\n\n/**\n * Base service class for handling CRUD operations on a specific model.\n * This class provides standard implementation of data operations that can be extended\n *\n * by model-specific service classes.\n *\n * @class BaseService\n *\n * @usage\n *\n * **Example:** creating a simple service\n *\n * ```ts\n * import { prisma } from '../../utils/prisma'\n *\n * const userService = new BaseService<typeof prisma.user>(\"user\")\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-reference/the-base-service-class}\n *\n */\nexport class BaseService<ModelDelegate extends Record<string, any> = any> {\n /**\n * The camelCase name of the model\n * @public\n */\n modelName: string;\n\n /**\n * Object containing singular and list relation fields for the model\n * @public\n */\n relationFields: RelationFields;\n\n /**\n * Instance of the Prisma client\n * @public\n */\n prisma: any;\n\n /**\n * Creates an instance of BaseService.\n * @param {string} modelName - The name of the model to perform operations on.\n */\n constructor(modelName: string) {\n this.modelName = camelCase(modelName);\n this.relationFields = getPrismaModelRelations(pascalCase(modelName))!;\n }\n\n /**\n * Creates a single record in the database.\n *\n * @param {Parameters<ModelDelegate[\"create\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to create the record with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"create\"]>>} The created record.\n */\n async createOne<\n TOptions extends Omit<Parameters<ModelDelegate[\"create\"]>[0], \"data\">,\n >(\n data: Parameters<ModelDelegate[\"create\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"create\"] extends (args: { data: any }) => infer R ? R : any\n > {\n // user uer Password123 true false Promise { true }\n if (kebabCase(this.modelName) === \"user\" && (data as any).password)\n if (!authService.isPasswordHashed((data as any).password))\n (data as any).password = await authService.hashPassword(\n (data as any).password\n );\n\n const prisma = getPrismaInstance();\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(\n data as Record<string, any>,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n\n return await (prisma[this.modelName] as ModelDelegate).create(\n deepmerge(\n {\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { data: any }\n );\n }\n\n /**\n * Creates multiple records in the database.\n *\n * @param {Parameters<ModelDelegate[\"createMany\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - An array of data to create records with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"createMany\"]>>} The result of the createMany operation.\n */\n async createMany<\n TOptions extends Omit<Parameters<ModelDelegate[\"createMany\"]>[0], \"data\">,\n >(\n data: Parameters<ModelDelegate[\"createMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"createMany\"] extends (args: { data: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (Array.isArray(data))\n (data as { [x: string]: any; password?: string }[]).forEach(\n async (curr, i) => {\n if (\"password\" in curr && this.modelName === \"user\")\n if (!authService.isPasswordHashed(curr.password!))\n curr.password = await authService.hashPassword(curr?.password!);\n\n data[i] = handleRelationFieldsInBody(\n data[i] as Record<string, any>,\n {\n ...this.relationFields,\n },\n [\"delete\", \"disconnect\", \"update\"]\n );\n }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).createMany(\n deepmerge({ data }, (queryOptions as {}) || {}) as {\n data: any;\n }\n );\n }\n\n /**\n * Counts records based on provided filters.\n *\n * @param {Parameters<ModelDelegate[\"count\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to apply to the query.\n * @returns {Promise<number>} The count of records matching the filters.\n */\n async count(\n filters: Parameters<ModelDelegate[\"count\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<number> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).count({\n where: filters,\n });\n }\n\n /**\n * Finds multiple records based on provided filters.\n *\n * @param {Parameters<ModelDelegate[\"findMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to apply to the query.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findMany\"]>>} The found data.\n */\n async findMany<\n TOptions extends Omit<Parameters<ModelDelegate[\"findMany\"]>[0], \"where\">,\n >(\n filters: Parameters<ModelDelegate[\"findMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findMany\"] extends (\n args: { where: any } & TOptions\n ) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).findMany(\n deepmerge({ where: filters }, (queryOptions as {}) || {}) as {\n where: any;\n } & TOptions\n );\n }\n\n /**\n * Finds a single record by its ID.\n *\n * @param {string | number} id - The ID of the record to find.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findUnique\"]>>} The found record or null if not found.\n */\n async findById<\n TOptions extends Omit<Parameters<ModelDelegate[\"findUnique\"]>[0], \"where\">,\n >(\n id: string | number,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findUnique\"] extends (args: { where: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).findUnique(\n deepmerge(\n {\n where: { id },\n },\n queryOptions || {}\n ) as { where: { id: string | number } }\n );\n }\n\n /**\n * Finds a single record by its parameters.\n *\n * @param {Parameters<ModelDelegate[\"findFirst\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any | Parameters<TModel[\"findUnique\"]>[0] extends { where: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"findFirst\"]> | ReturnType<TModel[\"findUnique\"]>>} The found record or null if not found.\n */\n async findOne<\n TOptions extends\n | Omit<Parameters<ModelDelegate[\"findFirst\"]>[0], \"where\">\n | Omit<Parameters<ModelDelegate[\"findUnique\"]>[0], \"where\">,\n >(\n filters: Parameters<ModelDelegate[\"findFirst\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any | Parameters<ModelDelegate[\"findUnique\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"findFirst\"] extends (args: { where: any }) => infer R\n ? R\n : ModelDelegate[\"findUnique\"] extends (args: { where: any }) => infer R2\n ? R2\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (\n Object.keys(filters as Record<string, any>).length === 1 &&\n \"id\" in (filters as Record<string, any>) &&\n (filters as any).id !== \"me\"\n )\n return (prisma[this.modelName] as ModelDelegate).findUnique(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).findFirst(\n deepmerge(\n {\n where: filters,\n },\n (queryOptions as {}) || {}\n ) as { where: any }\n );\n }\n\n /**\n * Updates a single record by its ID.\n *\n * @param {Parameters<ModelDelegate[\"update\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @param {Parameters<ModelDelegate[\"update\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to update the record with.\n * @param {TOptions} [queryOptions] - Additional query options to modify the Prisma query.\n * @returns {Promise<ReturnType<ModelDelegate[\"update\"]>>} The updated record or null if not found.\n */\n async updateOne<\n TOptions extends Omit<\n Parameters<ModelDelegate[\"update\"]>[0],\n \"where\" | \"data\"\n >,\n >(\n filters: Parameters<ModelDelegate[\"update\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<ModelDelegate[\"update\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"update\"] extends (args: { where: any; data: any }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (kebabCase(this.modelName) === \"user\" && (data as any)?.password) {\n if (!authService.isPasswordHashed((data as any).password!))\n (data as any).password = await authService.hashPassword(\n (data as any)?.password\n );\n }\n\n const dataWithRelationFieldsHandled = handleRelationFieldsInBody(\n data as Record<string, any>,\n {\n ...this.relationFields,\n }\n );\n\n return await (prisma[this.modelName] as ModelDelegate).update(\n deepmerge(\n {\n where: filters,\n data: dataWithRelationFieldsHandled,\n },\n (queryOptions as {}) || {}\n ) as { where: any; data: any }\n );\n }\n\n /**\n * Updates multiple records based on the provided filter and data.\n *\n * @param {Parameters<ModelDelegate[\"updateMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The filters to identify records to update.\n * @param {Parameters<ModelDelegate[\"updateMany\"]>[0] extends { data: infer D; [x: string]: any } ? D : any} data - The data to update the records with.\n * @param {TOptions} [queryOptions] - Additional query options.\n * @returns {Promise<ReturnType<ModelDelegate[\"updateMany\"]>>} The result of the updateMany operation.\n */\n async updateMany<\n TOptions extends Omit<\n Parameters<ModelDelegate[\"updateMany\"]>[0],\n \"where\" | \"data\"\n >,\n >(\n filters: Parameters<ModelDelegate[\"updateMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any,\n data: Parameters<ModelDelegate[\"updateMany\"]>[0] extends {\n data: infer D;\n [x: string]: any;\n }\n ? D\n : any,\n queryOptions?: TOptions\n ): Promise<\n ModelDelegate[\"updateMany\"] extends (args: {\n where: any;\n data: any;\n }) => infer R\n ? R\n : any\n > {\n const prisma = getPrismaInstance();\n\n if (Array.isArray(data) && this.modelName === \"user\")\n (data as { [x: string]: any; password?: string }[]).forEach(\n async (curr, i) => {\n if (\"password\" in data[i])\n if (!authService.isPasswordHashed(curr.password!))\n (data[i] as any).password = await authService.hashPassword(\n curr.password!\n );\n }\n );\n\n const firstMerge = deepmerge({ data }, (queryOptions as {}) || {});\n\n return await (prisma[this.modelName] as ModelDelegate).updateMany(\n deepmerge({ where: filters }, firstMerge) as {\n where: any;\n data: any;\n }\n );\n }\n\n /**\n * Deletes a single record by its ID.\n *\n * @param {Parameters<ModelDelegate[\"delete\"]>[0] extends { where?: infer W; [x: string]: any } ? W : any} filters - The parameters to find the record by.\n * @returns {Promise<ReturnType<ModelDelegate[\"delete\"]>>} The deleted record or null if an error occurs.\n */\n async deleteOne(\n filters: Parameters<ModelDelegate[\"delete\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : any\n ): Promise<ReturnType<ModelDelegate[\"delete\"]>> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).delete({\n where: filters,\n });\n }\n\n /**\n * Deletes multiple records based on the provided filter.\n *\n * @param {Parameters<ModelDelegate[\"deleteMany\"]>[0] extends { where?: infer W; [x: string]: any } ? W : Record<string, any>} filters - The filter to identify records to delete.\n * @returns {Promise<ReturnType<ModelDelegate[\"deleteMany\"]>>} The result of the deleteMany operation.\n */\n async deleteMany(\n filters: Parameters<ModelDelegate[\"deleteMany\"]>[0] extends {\n where?: infer W;\n [x: string]: any;\n }\n ? W\n : Record<string, any>\n ): Promise<ReturnType<ModelDelegate[\"deleteMany\"]>> {\n const prisma = getPrismaInstance();\n\n return await (prisma[this.modelName] as ModelDelegate).deleteMany({\n where: filters,\n });\n }\n}\n\n/**\n * Generates a set of base service instances for all available models.\n *\n * @returns {Record<string, BaseService>} A dictionary of base service instances, keyed by model name.\n */\nexport function getBaseServices(): Record<string, BaseService<any>> {\n const models = getModels();\n const baseServices: Record<string, BaseService<any>> = {};\n models.forEach((model) => {\n baseServices[`${camelCase(model)}`] = new BaseService(model);\n });\n return baseServices;\n}\n"]}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.resolvePrismaQueryOptions = resolvePrismaQueryOptions;
|
|
7
|
+
const deepmerge_helper_1 = __importDefault(require("../../../../utils/helpers/deepmerge.helper"));
|
|
8
|
+
function resolvePrismaQueryOptions(prismaQueryOptions, action) {
|
|
9
|
+
if (!prismaQueryOptions) {
|
|
10
|
+
return {};
|
|
11
|
+
}
|
|
12
|
+
const options = prismaQueryOptions;
|
|
13
|
+
const actionOptions = options[action] || {};
|
|
14
|
+
let mergedOptions = options.queryOptions || {};
|
|
15
|
+
if (options.global) {
|
|
16
|
+
mergedOptions = (0, deepmerge_helper_1.default)(mergedOptions, options.global);
|
|
17
|
+
}
|
|
18
|
+
const generalOptions = getGeneralOptionsForAction(options, action);
|
|
19
|
+
if (generalOptions) {
|
|
20
|
+
mergedOptions = (0, deepmerge_helper_1.default)(mergedOptions, generalOptions);
|
|
21
|
+
}
|
|
22
|
+
if (actionOptions) {
|
|
23
|
+
mergedOptions = (0, deepmerge_helper_1.default)(mergedOptions, actionOptions);
|
|
24
|
+
}
|
|
25
|
+
return mergedOptions;
|
|
26
|
+
}
|
|
27
|
+
function getGeneralOptionsForAction(options, action) {
|
|
28
|
+
const actionMappings = {
|
|
29
|
+
findMany: ["find"],
|
|
30
|
+
findOne: ["find"],
|
|
31
|
+
create: ["create", "save"],
|
|
32
|
+
createOne: ["create", "save", "saveOne"],
|
|
33
|
+
createMany: ["create", "save", "saveMany"],
|
|
34
|
+
update: ["update", "save"],
|
|
35
|
+
updateOne: ["update", "save", "saveOne"],
|
|
36
|
+
updateMany: ["update", "save", "saveMany"],
|
|
37
|
+
delete: ["delete"],
|
|
38
|
+
deleteOne: ["delete"],
|
|
39
|
+
deleteMany: ["delete"],
|
|
40
|
+
};
|
|
41
|
+
const generalKeys = actionMappings[action] || [];
|
|
42
|
+
let generalOptions = {};
|
|
43
|
+
for (const key of generalKeys) {
|
|
44
|
+
if (options[key]) {
|
|
45
|
+
generalOptions = (0, deepmerge_helper_1.default)(generalOptions, options[key]);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return Object.keys(generalOptions).length > 0 ? generalOptions : null;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=base.middlewares.helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"base.middlewares.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.middlewares.helpers.ts"],"names":[],"mappings":";;;;;AAYA,8DA+BC;AA1CD,kGAAmE;AAWnE,SAAgB,yBAAyB,CACvC,kBAAqE,EACrE,MAAyB;IAEzB,IAAI,CAAC,kBAAkB,EAAE,CAAC;QACxB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,OAAO,GAAG,kBAAyB,CAAC;IAC1C,MAAM,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IAG5C,IAAI,aAAa,GAAG,OAAO,CAAC,YAAY,IAAI,EAAE,CAAC;IAG/C,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;QACnB,aAAa,GAAG,IAAA,0BAAS,EAAC,aAAa,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3D,CAAC;IAGD,MAAM,cAAc,GAAG,0BAA0B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IACnE,IAAI,cAAc,EAAE,CAAC;QACnB,aAAa,GAAG,IAAA,0BAAS,EAAC,aAAa,EAAE,cAAc,CAAC,CAAC;IAC3D,CAAC;IAGD,IAAI,aAAa,EAAE,CAAC;QAClB,aAAa,GAAG,IAAA,0BAAS,EAAC,aAAa,EAAE,aAAa,CAAC,CAAC;IAC1D,CAAC;IAED,OAAO,aAAa,CAAC;AACvB,CAAC;AASD,SAAS,0BAA0B,CACjC,OAAY,EACZ,MAAyB;IAGzB,MAAM,cAAc,GAA6B;QAE/C,QAAQ,EAAE,CAAC,MAAM,CAAC;QAClB,OAAO,EAAE,CAAC,MAAM,CAAC;QAGjB,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,SAAS,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAC;QACxC,UAAU,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAC;QAG1C,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,SAAS,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAC;QACxC,UAAU,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAC;QAG1C,MAAM,EAAE,CAAC,QAAQ,CAAC;QAClB,SAAS,EAAE,CAAC,QAAQ,CAAC;QACrB,UAAU,EAAE,CAAC,QAAQ,CAAC;KACvB,CAAC;IAEF,MAAM,WAAW,GAAG,cAAc,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IACjD,IAAI,cAAc,GAAG,EAAE,CAAC;IAGxB,KAAK,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC;QAC9B,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACjB,cAAc,GAAG,IAAA,0BAAS,EAAC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC;AACxE,CAAC","sourcesContent":["import { AuthPrismaQueryOptions, PrismaQueryOptions } from \"../../../../types\";\nimport deepmerge from \"../../../../utils/helpers/deepmerge.helper\";\nimport { ControllerActions } from \"../../base.middlewares\";\n\n/**\n * Helper function to resolve and merge Prisma query options based on action and general options\n *\n * @template T - The type of the Prisma model\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options\n * @param {ControllerActions} action - The controller action to apply\n * @returns {Record<string, any>} The merged query options for the specific action\n */\nexport function resolvePrismaQueryOptions<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n): Record<string, any> {\n if (!prismaQueryOptions) {\n return {};\n }\n\n const options = prismaQueryOptions as any;\n const actionOptions = options[action] || {};\n\n // Start with deprecated queryOptions (for backward compatibility)\n let mergedOptions = options.queryOptions || {};\n\n // Apply global options (replaces queryOptions)\n if (options.global) {\n mergedOptions = deepmerge(mergedOptions, options.global);\n }\n\n // Apply general operation options based on action type\n const generalOptions = getGeneralOptionsForAction(options, action);\n if (generalOptions) {\n mergedOptions = deepmerge(mergedOptions, generalOptions);\n }\n\n // Finally apply specific action options (highest priority)\n if (actionOptions) {\n mergedOptions = deepmerge(mergedOptions, actionOptions);\n }\n\n return mergedOptions;\n}\n\n/**\n * Helper function to get general options based on the action type\n *\n * @param {any} options - The Prisma query options object\n * @param {ControllerActions} action - The controller action\n * @returns {Record<string, any> | null} The general options for the action type\n */\nfunction getGeneralOptionsForAction(\n options: any,\n action: ControllerActions\n): Record<string, any> | null {\n // Map actions to their general option categories\n const actionMappings: Record<string, string[]> = {\n // Find operations\n findMany: [\"find\"],\n findOne: [\"find\"],\n\n // Create operations\n create: [\"create\", \"save\"],\n createOne: [\"create\", \"save\", \"saveOne\"],\n createMany: [\"create\", \"save\", \"saveMany\"],\n\n // Update operations\n update: [\"update\", \"save\"],\n updateOne: [\"update\", \"save\", \"saveOne\"],\n updateMany: [\"update\", \"save\", \"saveMany\"],\n\n // Delete operations\n delete: [\"delete\"],\n deleteOne: [\"delete\"],\n deleteMany: [\"delete\"],\n };\n\n const generalKeys = actionMappings[action] || [];\n let generalOptions = {};\n\n // Merge all applicable general options in order of precedence\n for (const key of generalKeys) {\n if (options[key]) {\n generalOptions = deepmerge(generalOptions, options[key]);\n }\n }\n\n return Object.keys(generalOptions).length > 0 ? generalOptions : null;\n}\n"]}
|