arkos 1.4.1-canary.8 → 1.5.0-canary.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/modules/auth/auth.controller.js +13 -0
- package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +40 -14
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/auth/utils/services/auth-action.service.js +1 -1
- package/dist/cjs/modules/auth/utils/services/auth-action.service.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +6 -4
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/utils/error-prettifier.js +185 -0
- package/dist/cjs/modules/base/utils/error-prettifier.js.map +1 -0
- package/dist/cjs/modules/email/email.service.js +4 -1
- package/dist/cjs/modules/email/email.service.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +9 -3
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +27 -9
- package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +28 -11
- package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
- package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
- package/dist/cjs/types/auth.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js +7 -1
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js +51 -0
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/cjs/utils/cli/generate.js +38 -0
- package/dist/cjs/utils/cli/generate.js.map +1 -1
- package/dist/cjs/utils/cli/index.js +37 -4
- package/dist/cjs/utils/cli/index.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/auth-configs-template.js +70 -37
- package/dist/cjs/utils/cli/utils/template-generator/templates/auth-configs-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +556 -0
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -0
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js +327 -0
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -0
- package/dist/cjs/utils/cli/utils/template-generators.js +14 -8
- package/dist/cjs/utils/cli/utils/template-generators.js.map +1 -1
- package/dist/cjs/utils/dynamic-loader.js +2 -2
- package/dist/cjs/utils/dynamic-loader.js.map +1 -1
- package/dist/cjs/utils/helpers/routers.helpers.js +2 -3
- package/dist/cjs/utils/helpers/routers.helpers.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +5 -5
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/esm/modules/auth/auth.controller.js +13 -0
- package/dist/esm/modules/auth/auth.controller.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +40 -14
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/auth/utils/services/auth-action.service.js +1 -1
- package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
- package/dist/esm/modules/base/base.middlewares.js +6 -4
- package/dist/esm/modules/base/base.middlewares.js.map +1 -1
- package/dist/esm/modules/base/utils/error-prettifier.js +181 -0
- package/dist/esm/modules/base/utils/error-prettifier.js.map +1 -0
- package/dist/esm/modules/email/email.service.js +4 -1
- package/dist/esm/modules/email/email.service.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +9 -3
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +27 -9
- package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +28 -11
- package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
- package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
- package/dist/esm/types/auth.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js +8 -2
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/index.js +50 -0
- package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/esm/utils/cli/generate.js +38 -0
- package/dist/esm/utils/cli/generate.js.map +1 -1
- package/dist/esm/utils/cli/index.js +37 -4
- package/dist/esm/utils/cli/index.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/auth-configs-template.js +70 -37
- package/dist/esm/utils/cli/utils/template-generator/templates/auth-configs-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +549 -0
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -0
- package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js +320 -0
- package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -0
- package/dist/esm/utils/cli/utils/template-generators.js +14 -8
- package/dist/esm/utils/cli/utils/template-generators.js.map +1 -1
- package/dist/esm/utils/dynamic-loader.js +2 -2
- package/dist/esm/utils/dynamic-loader.js.map +1 -1
- package/dist/esm/utils/helpers/routers.helpers.js +2 -3
- package/dist/esm/utils/helpers/routers.helpers.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js +5 -5
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/types/modules/auth/auth.service.d.ts +5 -0
- package/dist/types/modules/auth/utils/services/auth-action.service.d.ts +1 -1
- package/dist/types/modules/base/utils/error-prettifier.d.ts +19 -0
- package/dist/types/modules/email/email.service.d.ts +4 -8
- package/dist/types/types/auth.d.ts +3 -3
- package/dist/types/utils/arkos-router/index.d.ts +3 -1
- package/dist/types/utils/arkos-router/types/index.d.ts +2 -2
- package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +4 -0
- package/dist/types/utils/cli/generate.d.ts +4 -0
- package/dist/types/utils/cli/utils/template-generator/templates/auth-configs-template.d.ts +3 -1
- package/dist/types/utils/cli/utils/template-generator/templates/class-validator-dto-generator.d.ts +18 -0
- package/dist/types/utils/cli/utils/template-generator/templates/zod-schema-generator.d.ts +14 -0
- package/dist/types/utils/helpers/routers.helpers.d.ts +1 -1
- package/package.json +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +0 -187
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +0 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +0 -181
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +0 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod/create-schema-template.js +0 -106
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod/create-schema-template.js.map +0 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod/update-schema-template.js +0 -104
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod/update-schema-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +0 -181
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +0 -175
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/zod/create-schema-template.js +0 -100
- package/dist/esm/utils/cli/utils/template-generator/templates/zod/create-schema-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/zod/update-schema-template.js +0 -98
- package/dist/esm/utils/cli/utils/template-generator/templates/zod/update-schema-template.js.map +0 -1
- package/dist/types/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.d.ts +0 -2
- package/dist/types/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.d.ts +0 -2
- package/dist/types/utils/cli/utils/template-generator/templates/zod/create-schema-template.d.ts +0 -2
- package/dist/types/utils/cli/utils/template-generator/templates/zod/update-schema-template.d.ts +0 -2
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ErrorPrettifier = void 0;
|
|
4
|
+
class ErrorPrettifier {
|
|
5
|
+
prettify(library, error) {
|
|
6
|
+
if (library === "class-validator") {
|
|
7
|
+
return this.prettifyClassValidator(error);
|
|
8
|
+
}
|
|
9
|
+
else {
|
|
10
|
+
return this.prettifyZod(error);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
toPascalCase(path) {
|
|
14
|
+
return path
|
|
15
|
+
.split(".")
|
|
16
|
+
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
17
|
+
.join("");
|
|
18
|
+
}
|
|
19
|
+
replaceFieldInMessage(message, fieldName, fullPath) {
|
|
20
|
+
if (!fullPath.includes(".") && !fullPath.includes("[")) {
|
|
21
|
+
return message;
|
|
22
|
+
}
|
|
23
|
+
const regex = new RegExp(`^${fieldName}\\b`, "i");
|
|
24
|
+
if (regex.test(message)) {
|
|
25
|
+
return message.replace(regex, fullPath);
|
|
26
|
+
}
|
|
27
|
+
const wordBoundaryRegex = new RegExp(`\\b${fieldName}\\b`, "gi");
|
|
28
|
+
if (wordBoundaryRegex.test(message)) {
|
|
29
|
+
return message.replace(wordBoundaryRegex, fullPath);
|
|
30
|
+
}
|
|
31
|
+
return `${fullPath} ${message}`;
|
|
32
|
+
}
|
|
33
|
+
prettifyClassValidator(errors, parentPath = "") {
|
|
34
|
+
const result = [];
|
|
35
|
+
for (const error of errors) {
|
|
36
|
+
const currentPath = parentPath
|
|
37
|
+
? `${parentPath}.${error.property}`
|
|
38
|
+
: error.property;
|
|
39
|
+
if (error.children && error.children.length > 0) {
|
|
40
|
+
result.push(...this.prettifyClassValidator(error.children, currentPath));
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (error.constraints) {
|
|
44
|
+
const fieldPascal = this.toPascalCase(currentPath);
|
|
45
|
+
for (const [constraintKey, originalMessage] of Object.entries(error.constraints)) {
|
|
46
|
+
const constraintName = constraintKey.charAt(0).toUpperCase() + constraintKey.slice(1);
|
|
47
|
+
const message = this.replaceFieldInMessage(originalMessage, error.property, currentPath);
|
|
48
|
+
result.push({
|
|
49
|
+
message: message,
|
|
50
|
+
code: `${fieldPascal}${constraintName}Constraint`,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
mapZodToConstraintName(issue) {
|
|
58
|
+
switch (issue.code) {
|
|
59
|
+
case "invalid_type":
|
|
60
|
+
const expected = issue.expected;
|
|
61
|
+
switch (expected) {
|
|
62
|
+
case "string":
|
|
63
|
+
return "IsStringConstraint";
|
|
64
|
+
case "number":
|
|
65
|
+
return "IsNumberConstraint";
|
|
66
|
+
case "boolean":
|
|
67
|
+
return "IsBooleanConstraint";
|
|
68
|
+
case "array":
|
|
69
|
+
return "IsArrayConstraint";
|
|
70
|
+
case "object":
|
|
71
|
+
return "IsObjectConstraint";
|
|
72
|
+
case "date":
|
|
73
|
+
return "IsDateConstraint";
|
|
74
|
+
default:
|
|
75
|
+
return "InvalidTypeConstraint";
|
|
76
|
+
}
|
|
77
|
+
case "too_small":
|
|
78
|
+
if (issue.type === "string") {
|
|
79
|
+
return "MinLengthConstraint";
|
|
80
|
+
}
|
|
81
|
+
else if (issue.type === "number") {
|
|
82
|
+
return "MinConstraint";
|
|
83
|
+
}
|
|
84
|
+
else if (issue.type === "array") {
|
|
85
|
+
return "ArrayMinSizeConstraint";
|
|
86
|
+
}
|
|
87
|
+
return "TooSmallConstraint";
|
|
88
|
+
case "too_big":
|
|
89
|
+
if (issue.type === "string") {
|
|
90
|
+
return "MaxLengthConstraint";
|
|
91
|
+
}
|
|
92
|
+
else if (issue.type === "number") {
|
|
93
|
+
return "MaxConstraint";
|
|
94
|
+
}
|
|
95
|
+
else if (issue.type === "array") {
|
|
96
|
+
return "ArrayMaxSizeConstraint";
|
|
97
|
+
}
|
|
98
|
+
return "TooBigConstraint";
|
|
99
|
+
case "invalid_string":
|
|
100
|
+
if ("validation" in issue) {
|
|
101
|
+
const validation = issue.validation;
|
|
102
|
+
if (validation === "email")
|
|
103
|
+
return "IsEmailConstraint";
|
|
104
|
+
if (validation === "uuid")
|
|
105
|
+
return "IsUuidConstraint";
|
|
106
|
+
if (validation === "url")
|
|
107
|
+
return "IsUrlConstraint";
|
|
108
|
+
if (typeof validation === "object" && "includes" in validation)
|
|
109
|
+
return "ContainsConstraint";
|
|
110
|
+
if (typeof validation === "object" && "startsWith" in validation)
|
|
111
|
+
return "StartsWithConstraint";
|
|
112
|
+
if (typeof validation === "object" && "endsWith" in validation)
|
|
113
|
+
return "EndsWithConstraint";
|
|
114
|
+
}
|
|
115
|
+
return "InvalidStringConstraint";
|
|
116
|
+
case "invalid_enum_value":
|
|
117
|
+
return "IsEnumConstraint";
|
|
118
|
+
case "invalid_literal":
|
|
119
|
+
return "EqualsConstraint";
|
|
120
|
+
case "unrecognized_keys":
|
|
121
|
+
return "UnrecognizedKeysConstraint";
|
|
122
|
+
case "invalid_union":
|
|
123
|
+
return "InvalidUnionConstraint";
|
|
124
|
+
case "invalid_date":
|
|
125
|
+
return "IsDateConstraint";
|
|
126
|
+
case "custom":
|
|
127
|
+
return "CustomConstraint";
|
|
128
|
+
default:
|
|
129
|
+
return "ValidationConstraint";
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
prettifyZod(error) {
|
|
133
|
+
const result = [];
|
|
134
|
+
for (const issue of error.issues) {
|
|
135
|
+
const fieldPath = issue.path
|
|
136
|
+
.map((segment, index) => {
|
|
137
|
+
if (typeof segment === "number") {
|
|
138
|
+
return `[${segment}]`;
|
|
139
|
+
}
|
|
140
|
+
return index === 0 ? segment : `.${segment}`;
|
|
141
|
+
})
|
|
142
|
+
.join("")
|
|
143
|
+
.replace(/\.\[/g, "[");
|
|
144
|
+
const fieldPascal = fieldPath
|
|
145
|
+
? this.toPascalCase(fieldPath.replace(/\[\d+\]/g, ""))
|
|
146
|
+
: "Root";
|
|
147
|
+
const constraintName = this.mapZodToConstraintName(issue);
|
|
148
|
+
const message = this.injectFieldPathInZodMessage(issue.message, fieldPath, issue);
|
|
149
|
+
result.push({
|
|
150
|
+
message: message,
|
|
151
|
+
code: `${fieldPascal}${constraintName}`,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
injectFieldPathInZodMessage(message, fieldPath, issue) {
|
|
157
|
+
if (!fieldPath) {
|
|
158
|
+
return message;
|
|
159
|
+
}
|
|
160
|
+
if (message === "Required") {
|
|
161
|
+
return `${fieldPath} is required`;
|
|
162
|
+
}
|
|
163
|
+
if (message.startsWith("String must")) {
|
|
164
|
+
return message.replace(/^String must/, `${fieldPath} must`);
|
|
165
|
+
}
|
|
166
|
+
if (message.startsWith("Number must")) {
|
|
167
|
+
return message.replace(/^Number must/, `${fieldPath} must`);
|
|
168
|
+
}
|
|
169
|
+
if (message.startsWith("Array must")) {
|
|
170
|
+
return message.replace(/^Array must/, `${fieldPath} must`);
|
|
171
|
+
}
|
|
172
|
+
if (message.startsWith("Expected")) {
|
|
173
|
+
return `${fieldPath} must be valid: ${message}`;
|
|
174
|
+
}
|
|
175
|
+
if (message.startsWith("Invalid ")) {
|
|
176
|
+
const type = message.replace("Invalid ", "").toLowerCase();
|
|
177
|
+
return `${fieldPath} must be a valid ${type}`;
|
|
178
|
+
}
|
|
179
|
+
return `${fieldPath} ${message}`;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
exports.ErrorPrettifier = ErrorPrettifier;
|
|
183
|
+
const errorPrettifier = new ErrorPrettifier();
|
|
184
|
+
exports.default = errorPrettifier;
|
|
185
|
+
//# sourceMappingURL=error-prettifier.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-prettifier.js","sourceRoot":"","sources":["../../../../../src/modules/base/utils/error-prettifier.ts"],"names":[],"mappings":";;;AA2CA,MAAa,eAAe;IAa1B,QAAQ,CACN,OAA0B,EAC1B,KAAmC;QAEnC,IAAI,OAAO,KAAK,iBAAiB,EAAE,CAAC;YAClC,OAAO,IAAI,CAAC,sBAAsB,CAAC,KAA0B,CAAC,CAAC;QACjE,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC,WAAW,CAAC,KAAiB,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC;IAcO,YAAY,CAAC,IAAY;QAC/B,OAAO,IAAI;aACR,KAAK,CAAC,GAAG,CAAC;aACV,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;aAC3D,IAAI,CAAC,EAAE,CAAC,CAAC;IACd,CAAC;IAoBO,qBAAqB,CAC3B,OAAe,EACf,SAAiB,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":["import { ValidationError } from \"class-validator\";\nimport { ZodError, ZodIssue } from \"zod\";\n\n/**\n * Prettified error result with consistent format\n */\nexport interface PrettifiedError {\n /** Human-readable error message */\n message: string;\n /** Field name + constraint type code (e.g., 'NameIsStringConstraint') */\n code: string;\n}\n\n/**\n * Supported validation library types\n */\nexport type ValidationLibrary = \"class-validator\" | \"zod\";\n\n/**\n * ErrorPrettifier class for normalizing validation errors from class-validator and Zod\n * into a consistent format with field name + constraint code pattern.\n *\n * @example\n * ```typescript\n * const prettifier = new ErrorPrettifier();\n *\n * // Class-validator example\n * const classValidatorErrors = await validate(userDto);\n * const prettified = prettifier.prettify('class-validator', classValidatorErrors);\n * // [{ message: 'name must be a string', code: 'NameIsStringConstraint' }]\n *\n * // Zod example\n * try {\n * schema.parse(data);\n * } catch (error) {\n * const prettified = prettifier.prettify('zod', error);\n * // [{ message: 'name must be a string', code: 'NameIsStringConstraint' }]\n * }\n *\n * // Nested errors\n * // [{ message: 'user.address.street must be a string', code: 'UserAddressStreetIsStringConstraint' }]\n * ```\n */\nexport class ErrorPrettifier {\n /**\n * Prettifies validation errors from class-validator or Zod into a consistent format.\n *\n * @param library - The validation library type ('class-validator' or 'zod')\n * @param error - The validation error(s) from the library\n * @returns Array of prettified errors with consistent message and code format\n */\n prettify(\n library: \"class-validator\",\n error: ValidationError[]\n ): PrettifiedError[];\n prettify(library: \"zod\", error: ZodError): PrettifiedError[];\n prettify(\n library: ValidationLibrary,\n error: ValidationError[] | ZodError\n ): PrettifiedError[] {\n if (library === \"class-validator\") {\n return this.prettifyClassValidator(error as ValidationError[]);\n } else {\n return this.prettifyZod(error as ZodError);\n }\n }\n\n /**\n * Converts a field path to PascalCase for code generation.\n *\n * @example\n * ```typescript\n * toPascalCase('user.address.street') // 'UserAddressStreet'\n * toPascalCase('email') // 'Email'\n * ```\n *\n * @param path - Dot-separated field path\n * @returns PascalCase version of the path\n */\n private toPascalCase(path: string): string {\n return path\n .split(\".\")\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\"\");\n }\n\n /**\n * Replaces the field name in the validation message with the full path.\n * Handles array indices like tags[0] and nested paths like user.address.street.\n *\n * @example\n * ```typescript\n * replaceFieldInMessage('id must be a UUID', 'id', 'user.id')\n * // Returns: 'user.id must be a UUID'\n *\n * replaceFieldInMessage('name must be a string', 'name', 'tags[0].name')\n * // Returns: 'tags[0].name must be a string'\n * ```\n *\n * @param message - Original validation message\n * @param fieldName - Original field name\n * @param fullPath - Full path including parent properties\n * @returns Message with field name replaced by full path\n */\n private replaceFieldInMessage(\n message: string,\n fieldName: string,\n fullPath: string\n ): string {\n // If it's a top-level field (no dots or brackets), return original message\n if (!fullPath.includes(\".\") && !fullPath.includes(\"[\")) {\n return message;\n }\n\n // Replace the field name at the start of the message with the full path\n // Handle cases like \"id must be a UUID\" -> \"user.id must be a UUID\"\n const regex = new RegExp(`^${fieldName}\\\\b`, \"i\");\n if (regex.test(message)) {\n return message.replace(regex, fullPath);\n }\n\n // If field name is not at the start, try to find it and replace\n // This handles cases like \"must be a valid id\" or other formats\n const wordBoundaryRegex = new RegExp(`\\\\b${fieldName}\\\\b`, \"gi\");\n if (wordBoundaryRegex.test(message)) {\n return message.replace(wordBoundaryRegex, fullPath);\n }\n\n // If we can't find the field name in the message, prepend the path\n return `${fullPath} ${message}`;\n }\n\n /**\n * Prettifies class-validator ValidationError array.\n * Handles nested validation errors recursively.\n *\n * @param errors - Array of ValidationError from class-validator\n * @param parentPath - Parent path for nested errors (used internally)\n * @returns Array of prettified errors\n */\n private prettifyClassValidator(\n errors: ValidationError[],\n parentPath: string = \"\"\n ): PrettifiedError[] {\n const result: PrettifiedError[] = [];\n\n for (const error of errors) {\n const currentPath = parentPath\n ? `${parentPath}.${error.property}`\n : error.property;\n\n // Handle nested errors\n if (error.children && error.children.length > 0) {\n result.push(\n ...this.prettifyClassValidator(error.children, currentPath)\n );\n continue;\n }\n\n // Handle constraints on current field\n if (error.constraints) {\n const fieldPascal = this.toPascalCase(currentPath);\n\n for (const [constraintKey, originalMessage] of Object.entries(\n error.constraints\n )) {\n // Convert constraint key to PascalCase (e.g., 'isString' -> 'IsString')\n const constraintName =\n constraintKey.charAt(0).toUpperCase() + constraintKey.slice(1);\n\n // Replace the field name in the message with the full path\n const message = this.replaceFieldInMessage(\n originalMessage,\n error.property,\n currentPath\n );\n\n result.push({\n message: message,\n code: `${fieldPascal}${constraintName}Constraint`,\n });\n }\n }\n }\n\n return result;\n }\n\n /**\n * Maps Zod error codes and validation info to class-validator style constraint names.\n *\n * @param issue - Zod validation issue\n * @returns Class-validator style constraint name\n */\n private mapZodToConstraintName(issue: ZodIssue): string {\n switch (issue.code) {\n case \"invalid_type\":\n const expected = issue.expected;\n switch (expected) {\n case \"string\":\n return \"IsStringConstraint\";\n case \"number\":\n return \"IsNumberConstraint\";\n case \"boolean\":\n return \"IsBooleanConstraint\";\n case \"array\":\n return \"IsArrayConstraint\";\n case \"object\":\n return \"IsObjectConstraint\";\n case \"date\":\n return \"IsDateConstraint\";\n default:\n return \"InvalidTypeConstraint\";\n }\n\n case \"too_small\":\n if (issue.type === \"string\") {\n return \"MinLengthConstraint\";\n } else if (issue.type === \"number\") {\n return \"MinConstraint\";\n } else if (issue.type === \"array\") {\n return \"ArrayMinSizeConstraint\";\n }\n return \"TooSmallConstraint\";\n\n case \"too_big\":\n if (issue.type === \"string\") {\n return \"MaxLengthConstraint\";\n } else if (issue.type === \"number\") {\n return \"MaxConstraint\";\n } else if (issue.type === \"array\") {\n return \"ArrayMaxSizeConstraint\";\n }\n return \"TooBigConstraint\";\n\n case \"invalid_string\":\n if (\"validation\" in issue) {\n const validation = issue.validation;\n if (validation === \"email\") return \"IsEmailConstraint\";\n if (validation === \"uuid\") return \"IsUuidConstraint\";\n if (validation === \"url\") return \"IsUrlConstraint\";\n if (typeof validation === \"object\" && \"includes\" in validation)\n return \"ContainsConstraint\";\n if (typeof validation === \"object\" && \"startsWith\" in validation)\n return \"StartsWithConstraint\";\n if (typeof validation === \"object\" && \"endsWith\" in validation)\n return \"EndsWithConstraint\";\n }\n return \"InvalidStringConstraint\";\n\n case \"invalid_enum_value\":\n return \"IsEnumConstraint\";\n\n case \"invalid_literal\":\n return \"EqualsConstraint\";\n\n case \"unrecognized_keys\":\n return \"UnrecognizedKeysConstraint\";\n\n case \"invalid_union\":\n return \"InvalidUnionConstraint\";\n\n case \"invalid_date\":\n return \"IsDateConstraint\";\n\n case \"custom\":\n return \"CustomConstraint\";\n\n default:\n return \"ValidationConstraint\";\n }\n }\n\n /**\n * Prettifies Zod ZodError.\n * Handles nested paths and multiple issues per field.\n *\n * @param error - ZodError from Zod validation\n * @returns Array of prettified errors\n */\n private prettifyZod(error: ZodError): PrettifiedError[] {\n const result: PrettifiedError[] = [];\n\n for (const issue of error.issues) {\n // Build the field path from the issue path\n const fieldPath = issue.path\n .map((segment, index) => {\n // Handle array indices: convert to bracket notation\n if (typeof segment === \"number\") {\n return `[${segment}]`;\n }\n // First segment doesn't need a dot prefix\n return index === 0 ? segment : `.${segment}`;\n })\n .join(\"\")\n .replace(/\\.\\[/g, \"[\"); // Clean up .[ to just [\n\n const fieldPascal = fieldPath\n ? this.toPascalCase(fieldPath.replace(/\\[\\d+\\]/g, \"\"))\n : \"Root\";\n\n // Map Zod error code to constraint name\n const constraintName = this.mapZodToConstraintName(issue);\n\n // Inject the field path into the message naturally\n const message = this.injectFieldPathInZodMessage(\n issue.message,\n fieldPath,\n issue\n );\n\n result.push({\n message: message,\n code: `${fieldPascal}${constraintName}`,\n });\n }\n\n return result;\n }\n\n /**\n * Injects the field path into Zod error messages naturally.\n *\n * @example\n * ```typescript\n * injectFieldPathInZodMessage('String must contain at least 100 character(s)', 'user.id', issue)\n * // Returns: 'user.id must contain at least 100 character(s)'\n *\n * injectFieldPathInZodMessage('Required', 'email', issue)\n * // Returns: 'email is required'\n * ```\n *\n * @param message - Original Zod error message\n * @param fieldPath - Full field path (e.g., 'user.id', 'tags[0].name')\n * @param issue - Zod issue for context\n * @returns Message with field path injected naturally\n */\n private injectFieldPathInZodMessage(\n message: string,\n fieldPath: string,\n issue: ZodIssue\n ): string {\n // If no field path (root level), return original message\n if (!fieldPath) {\n return message;\n }\n\n // Handle common Zod message patterns\n\n // \"Required\" -> \"fieldPath is required\"\n if (message === \"Required\") {\n return `${fieldPath} is required`;\n }\n\n // \"String must...\" -> \"fieldPath must...\"\n if (message.startsWith(\"String must\")) {\n return message.replace(/^String must/, `${fieldPath} must`);\n }\n\n // \"Number must...\" -> \"fieldPath must...\"\n if (message.startsWith(\"Number must\")) {\n return message.replace(/^Number must/, `${fieldPath} must`);\n }\n\n // \"Array must...\" -> \"fieldPath must...\"\n if (message.startsWith(\"Array must\")) {\n return message.replace(/^Array must/, `${fieldPath} must`);\n }\n\n // \"Expected string, received number\" -> \"fieldPath: Expected string, received number\"\n if (message.startsWith(\"Expected\")) {\n return `${fieldPath} must be valid: ${message}`;\n }\n\n // \"Invalid email\" -> \"fieldPath must be a valid email\"\n if (message.startsWith(\"Invalid \")) {\n const type = message.replace(\"Invalid \", \"\").toLowerCase();\n return `${fieldPath} must be a valid ${type}`;\n }\n\n // For any other message, prepend the field path\n return `${fieldPath} ${message}`;\n }\n}\n\nconst errorPrettifier = new ErrorPrettifier();\n\nexport default errorPrettifier;\n"]}
|
|
@@ -74,7 +74,10 @@ class EmailService {
|
|
|
74
74
|
const info = await transporter.sendMail({
|
|
75
75
|
...options,
|
|
76
76
|
from: fromAddress,
|
|
77
|
-
text: options?.text ||
|
|
77
|
+
text: options?.text ||
|
|
78
|
+
(typeof options.html === "string" && options.html
|
|
79
|
+
? (0, html_to_text_1.convert)(options.html)
|
|
80
|
+
: undefined),
|
|
78
81
|
});
|
|
79
82
|
return { success: true, ...info };
|
|
80
83
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAqD;AACrD,+CAAuC;AACvC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;QAErE,IAAI,iBAAiB,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAC3C,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;YAC7D,IAAI,CAAC,WAAW;gBAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;QACzE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,WAAW,CAAC,QAAQ,CAAC;YACtC,GAAG,OAAO;YACV,IAAI,EAAE,WAAW;YACjB,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,IAAA,sBAAO,EAAC,OAAO,CAAC,IAAI,CAAC;SAC7C,CAAC,CAAC;QAEH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,CAAC;IACpC,CAAC;IAOM,KAAK,CAAC,gBAAgB,CAC3B,mBAAiC;QAEjC,IAAI,CAAC;YACH,MAAM,WAAW,GAAG,mBAAmB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACjE,MAAM,WAAW,CAAC,MAAM,EAAE,CAAC;YAC3B,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAMM,YAAY,CAAC,MAA6B;QAC/C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAOM,MAAM,CAAC,MAAM,CAAC,MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AA5JD,oCA4JC;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,kBAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n from?: string;\n to: string | string[];\n subject: string;\n text?: string;\n html: string;\n};\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/api-reference/the-email-service-class](https://www.arkosjs.com/docs/api-reference/the-email-service-class)\n */\nexport class EmailService {\n private transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host || !user || !pass) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST, EMAIL_USER, EMAIL_PASSWORD)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/core-concepts/sending-emails\",\n }\n );\n }\n\n return {\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth: {\n user,\n pass,\n },\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress,\n text: options?.text || convert(options.html),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
|
|
1
|
+
{"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAsE;AACtE,+CAAuC;AACvC,yCAA8C;AAC9C,iFAAwD;AAiCxD,MAAa,YAAY;IAUvB,YAAY,MAA8B;QAT1C,gBAAW,GAAuB,IAAI,CAAC;QAC/B,iBAAY,GAAiC,IAAI,CAAC;QASxD,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC7B,CAAC;IACH,CAAC;IAUO,cAAc;QACpB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,OAAO,IAAI,CAAC,YAAY,CAAC;QAC3B,CAAC;QAED,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;QACjD,MAAM,IAAI,GAAG,YAAY,EAAE,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;QAC1D,MAAM,IAAI,GACR,YAAY,EAAE,IAAI;YAClB,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,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gBAAgB,CAC3B,mBAAiC;QAEjC,IAAI,CAAC;YACH,MAAM,WAAW,GAAG,mBAAmB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACjE,MAAM,WAAW,CAAC,MAAM,EAAE,CAAC;YAC3B,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAMM,YAAY,CAAC,MAA6B;QAC/C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAOM,MAAM,CAAC,MAAM,CAAC,MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AAhKD,oCAgKC;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,kBAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { SendMailOptions, Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n subject: string;\n} & SendMailOptions;\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/api-reference/the-email-service-class](https://www.arkosjs.com/docs/api-reference/the-email-service-class)\n */\nexport class EmailService {\n transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host || !user || !pass) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST, EMAIL_USER, EMAIL_PASSWORD)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/core-concepts/sending-emails\",\n }\n );\n }\n\n return {\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth: {\n user,\n pass,\n },\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions & SendMailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress,\n text:\n options?.text ||\n (typeof options.html === \"string\" && options.html\n ? convert(options.html as string)\n : undefined),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAyEC;AA3FD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE5D,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;IAEnD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B;QAC5C,KAAK,GAAG,qBAAqB,CAAC,iCAAiC,CAAC,GAAG,CAAC,CAAC;IACvE,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAiC;QAChD,KAAK,GAAG,qBAAqB,CAAC,qCAAqC,CAAC,GAAG,CAAC,CAAC;IAC3E,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO;QACtB,KAAK,GAAG,qBAAqB,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC;IAC/D,IAAI,G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3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message:\n err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAwEC;AA1FD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KA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AO;gBACf,OAAO,EAAE,gDAAgD;gBACzD,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,EAAE;aACT,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,SAAS;SAChB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message:\n err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
@@ -40,6 +40,7 @@ exports.handleDataTypeError = handleDataTypeError;
|
|
|
40
40
|
exports.handleEmptyResultError = handleEmptyResultError;
|
|
41
41
|
exports.handleNonExistingRecord = handleNonExistingRecord;
|
|
42
42
|
exports.handlePrismaClientInitializationError = handlePrismaClientInitializationError;
|
|
43
|
+
const change_case_features_1 = require("../../../utils/features/change-case.features");
|
|
43
44
|
const app_error_1 = __importDefault(require("./app-error"));
|
|
44
45
|
function handleJWTError() {
|
|
45
46
|
return new app_error_1.default("Invalid token. Please log in again!", 401);
|
|
@@ -83,7 +84,9 @@ function handleRecordNotFoundError(_) {
|
|
|
83
84
|
function handleUniqueConstraintError(err) {
|
|
84
85
|
const field = err?.meta?.target || "unknown field";
|
|
85
86
|
const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;
|
|
86
|
-
return new app_error_1.default(message, 409
|
|
87
|
+
return new app_error_1.default(message, 409, (err.meta?.modelName &&
|
|
88
|
+
`${(0, change_case_features_1.pascalCase)(err.meta?.modelName)}${(0, change_case_features_1.pascalCase)(err.meta?.target?.[0])}UniqueConstraint`) ||
|
|
89
|
+
"Unknown");
|
|
87
90
|
}
|
|
88
91
|
function handleForeignKeyConstraintError(_) {
|
|
89
92
|
const message = "Foreign key constraint violation. Ensure that the referenced record exists.";
|
|
@@ -197,9 +200,12 @@ function handleEmptyResultError(_) {
|
|
|
197
200
|
function handleNonExistingRecord(err) {
|
|
198
201
|
const message = err?.meta?.cause ||
|
|
199
202
|
`Operation could not be completed as the required record was not found`;
|
|
200
|
-
|
|
203
|
+
const model = err?.meta?.cause
|
|
204
|
+
? err?.meta?.cause?.split("No '")?.[1]?.split?.("'")?.[0]
|
|
205
|
+
: "";
|
|
206
|
+
return new app_error_1.default(message, 404, `Inline${(0, change_case_features_1.pascalCase)(model || "")}RecordNotFound`);
|
|
201
207
|
}
|
|
202
208
|
function handlePrismaClientInitializationError(_) {
|
|
203
|
-
return new app_error_1.default("Service temporarily unavailable", 503,
|
|
209
|
+
return new app_error_1.default("Service temporarily unavailable", 503, "DatabaseNotAvailable");
|
|
204
210
|
}
|
|
205
211
|
//# sourceMappingURL=error-handler.helpers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AASA,wCAEC;AAED,4CAEC;AAED,8EAIC;AAED,8DAIC;AAED,sEAIC;AAED,oEAIC;AAED,kEAGC;AAED,wEAIC;AAED,sEAGC;AAED,8DAIC;AAED,kEAIC;AAED,0EAIC;AAED,kEAIC;AAED,oEAIC;AAED,0EAIC;AAED,8DAIC;AAED,0DAIC;AAED,sEAIC;AAED,oEAIC;AAED,gFAIC;AAED,0EAIC;AAED,gFAIC;AAED,4EAIC;AAED,gEAGC;AAED,oEAIC;AAED,wDAGC;AAED,0DAGC;AAED,sDAGC;AAED,0DAGC;AAED,gEAIC;AAED,8CAIC;AAED,gDAGC;AAED,kEAGC;AAED,kDAKC;AAED,wDAGC;AAED,0DAQC;AAED,sFAOC;AA/ND,4DAAmC;AASnC,SAAgB,cAAc;IAC5B,OAAO,IAAI,mBAAQ,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC;AAED,SAAgB,gBAAgB;IAC9B,OAAO,IAAI,mBAAQ,CAAC,2CAA2C,EAAE,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAgB,iCAAiC,CAAC,GAAa;IAC7D,MAAM,OAAO,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G,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,uBAAuB,CAAC,GAGvC;IACC,MAAM,OAAO,GACX,GAAG,EAAE,IAAI,EAAE,KAAK;QAChB,uEAAuE,CAAC;IAC1E,OAAO,IAAI,mBAAQ,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,gBAAgB,CAAC,CAAC;AACtE,CAAC;AAED,SAAgB,qCAAqC,CAAC,CAAM;IAC1D,OAAO,IAAI,mBAAQ,CACjB,iCAAiC,EACjC,GAAG,EACH,EAAE,EACF,sBAAsB,CACvB,CAAC;AACJ,CAAC","sourcesContent":["import AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string;\n message: string;\n meta?: Record<string, any>;\n name?: string;\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message =\n err?.message?.split(\"\\n\")[err?.message?.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(_: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(_: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(_: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(_: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(message, 409);\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(_: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(_: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(_: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(_: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(_: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(_: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(_: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(_: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(_: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(_: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(_: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as the required record was not found`;\n return new AppError(message, 404, err.meta || {}, \"RecordNotFound\");\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n {},\n \"DatabaseNotAvailable\"\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.helpers.js","sourceRoot":"","sources":["../../../../../src/modules/error-handler/utils/error-handler.helpers.ts"],"names":[],"mappings":";;;;;AAUA,wCAEC;AAED,4CAEC;AAED,8EAIC;AAED,8DAIC;AAED,sEAIC;AAED,oEAIC;AAED,kEAGC;AAED,wEAIC;AAED,sEAGC;AAED,8DAIC;AAED,kEAUC;AAED,0EAIC;AAED,kEAIC;AAED,oEAIC;AAED,0EAIC;AAED,8DAIC;AAED,0DAIC;AAED,sEAIC;AAED,oEAIC;AAED,gFAIC;AAED,0EAIC;AAED,gFAIC;AAED,4EAIC;AAED,gEAGC;AAED,oEAIC;AAED,wDAGC;AAED,0DAGC;AAED,sDAGC;AAED,0DAGC;AAED,gEAIC;AAED,8CAIC;AAED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vB,CAAC;AACJ,CAAC","sourcesContent":["import { pascalCase } from \"../../../utils/features/change-case.features\";\nimport AppError from \"./app-error\";\n\nexport interface PrismaError {\n code?: string;\n message: string;\n meta?: Record<string, any>;\n name?: string;\n}\n\nexport function handleJWTError() {\n return new AppError(\"Invalid token. Please log in again!\", 401);\n}\n\nexport function handleJWTExpired() {\n return new AppError(\"Your token has expired, Please log again!\", 401);\n}\n\nexport function handlePrismaClientValidationError(err: AppError) {\n const message =\n err?.message?.split(\"\\n\")[err?.message?.split(\"\\n\").length - 1];\n return new AppError(message, 400);\n}\n\nexport function handleAuthenticationError(_: AppError) {\n const message =\n \"Authentication failed against the database server. Please check your credentials.\";\n return new AppError(message, 401);\n}\n\nexport function handleServerNotReachableError(_: AppError) {\n const message =\n \"The database server is not reachable. Verify your connection string or ensure the server is online.\";\n return new AppError(message, 503);\n}\n\nexport function handleConnectionTimeoutError(_: AppError) {\n const message =\n \"Connection to the database timed out. Please check server performance or network connectivity.\";\n return new AppError(message, 504);\n}\n\nexport function handleDatabaseNotFoundError(_: AppError) {\n const message = \"The specified database does not exist on the server.\";\n return new AppError(message, 404);\n}\n\nexport function handleEnvironmentVariableError(err: AppError) {\n const missingVars = err?.missing || \"unknown environment variables\";\n const message = `Missing or invalid environment variables: ${missingVars}. Please check your configuration.`;\n return new AppError(message, 500);\n}\n\nexport function handleFieldValueTooLargeError(err: AppError) {\n const message = `The value for the field \"${err?.meta?.field_name}\" is too large. Please provide a smaller value.`;\n return new AppError(message, 400);\n}\n\nexport function handleRecordNotFoundError(_: AppError) {\n const message =\n \"No record found for the given query. Ensure the query parameters are correct.\";\n return new AppError(message, 404);\n}\n\nexport function handleUniqueConstraintError(err: AppError) {\n const field = err?.meta?.target || \"unknown field\";\n const message = `Duplicate value detected for the unique field(s): ${field}. Please use a different value.`;\n return new AppError(\n message,\n 409,\n (err.meta?.modelName &&\n `${pascalCase(err.meta?.modelName)}${pascalCase(err.meta?.target?.[0])}UniqueConstraint`) ||\n \"Unknown\"\n );\n}\n\nexport function handleForeignKeyConstraintError(_: AppError) {\n const message =\n \"Foreign key constraint violation. Ensure that the referenced record exists.\";\n return new AppError(message, 400);\n}\n\nexport function handleConstraintFailedError(err: AppError) {\n const constraint = err?.meta?.constraint || \"unknown constraint\";\n const message = `A database constraint \"${constraint}\" failed. Please review your input data.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldValueError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `Invalid value provided for the field \"${fieldName}\". Please provide a valid value.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidFieldProvidedError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" has been provided with an invalid value. Check the data and try again.`;\n return new AppError(message, 400);\n}\n\nexport function handleDataValidationError(_: AppError) {\n const message =\n \"Data validation error occurred. Please ensure all fields meet the required criteria.\";\n return new AppError(message, 400);\n}\n\nexport function handleQueryParsingError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `Failed to parse the query: \"${query}\". Check the syntax and structure.`;\n return new AppError(message, 400);\n}\n\nexport function handleInvalidQueryFormatError(err: AppError) {\n const query = err?.meta?.query || \"unknown query\";\n const message = `The query format is invalid: \"${query}\". Ensure the query adheres to the expected format.`;\n return new AppError(message, 400);\n}\n\nexport function handleRawQueryExecutionError(_: AppError) {\n const message =\n \"An error occurred during the execution of a raw query. Verify the query and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleNullConstraintViolationError(err: AppError) {\n const fieldName = err?.meta?.field_name || \"unknown field\";\n const message = `The field \"${fieldName}\" cannot be null. Please provide a value.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaCreationFailedError(_: AppError) {\n const message =\n \"Failed to create the database schema. Verify the schema definition and try again.\";\n return new AppError(message, 500);\n}\n\nexport function handleMigrationAlreadyAppliedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration \"${migrationName}\" has already been applied to the database.`;\n return new AppError(message, 409);\n}\n\nexport function handleMigrationScriptFailedError(err: AppError) {\n const migrationName = err?.meta?.migration || \"unknown migration\";\n const message = `The migration script \"${migrationName}\" failed. Review the script and resolve any issues.`;\n return new AppError(message, 500);\n}\n\nexport function handleVersionMismatchError(_: AppError) {\n const message = `Version mismatch: The database schema and migration versions are inconsistent. Please check and resolve this issue.`;\n return new AppError(message, 400);\n}\n\nexport function handleMigrationFileReadError(err: AppError) {\n const migrationFile = err?.meta?.migration_file || \"unknown file\";\n const message = `Failed to read the migration file \"${migrationFile}\". Ensure the file exists and is accessible.`;\n return new AppError(message, 500);\n}\n\nexport function handleSchemaDriftError(_: AppError) {\n const message = `Schema drift detected: The database schema differs from the expected state. Run migrations or sync schema to resolve.`;\n return new AppError(message, 400);\n}\n\nexport function handleSchemaSyntaxError(_: AppError) {\n const message = `Syntax error in the schema file. Please check for typos or invalid syntax in your schema definition.`;\n return new AppError(message, 500);\n}\n\nexport function handleClientTypeError(_: AppError) {\n const message = `Type error, Ensure proper usage of methods and correct data types.`;\n return new AppError(message, 400);\n}\n\nexport function handleDynamicQueryError(_: AppError) {\n const message = `Error constructing or executing a dynamic query. Verify query structure and parameters.`;\n return new AppError(message, 400);\n}\n\nexport function handleRelationLoadingError(err: AppError) {\n const relation = err?.meta?.relation || \"unknown relation\";\n const message = `Error loading relation \"${relation}\". Ensure it is correctly defined and included in the query.`;\n return new AppError(message, 400);\n}\n\nexport function handleBinaryError(err: AppError) {\n const binaryName = err?.meta?.binary || \"unknown binary\";\n const message = `Error with Prisma binary \"${binaryName}\". Ensure the binary is properly installed and compatible.`;\n return new AppError(message, 500);\n}\n\nexport function handleNetworkError(_: AppError) {\n const message = `Network error: Unable to connect to the database or internet. Please check your network connection.`;\n return new AppError(message, 500);\n}\n\nexport function handleUnhandledPromiseError(_: AppError) {\n const message = `Unhandled promise rejection detected. Please check asynchronous code for proper error handling.`;\n return new AppError(message, 500);\n}\n\nexport function handleDataTypeError(err: AppError) {\n const field = err?.meta?.field || \"unknown field\";\n const expectedType = err?.meta?.expected_type || \"unknown type\";\n const message = `Invalid data type for field \"${field}\". Expected type: ${expectedType}.`;\n return new AppError(message, 400);\n}\n\nexport function handleEmptyResultError(_: AppError) {\n const message = `Empty result: No data was found for the given query. Ensure the query criteria are correct.`;\n return new AppError(message, 404);\n}\n\nexport function handleNonExistingRecord(err: {\n meta?: Record<string, any>;\n [x: string]: any;\n}) {\n const message =\n err?.meta?.cause ||\n `Operation could not be completed as the required record was not found`;\n\n const model = err?.meta?.cause\n ? err?.meta?.cause?.split(\"No '\")?.[1]?.split?.(\"'\")?.[0]\n : \"\";\n\n return new AppError(\n message,\n 404,\n `Inline${pascalCase(model || \"\")}RecordNotFound`\n );\n}\n\nexport function handlePrismaClientInitializationError(_: any) {\n return new AppError(\n \"Service temporarily unavailable\",\n 503,\n \"DatabaseNotAvailable\"\n );\n}\n"]}
|
|
@@ -44,7 +44,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
|
|
|
44
44
|
: currentPath?.summary,
|
|
45
45
|
description: currentPath?.description ||
|
|
46
46
|
"Authenticates a user and returns an access token",
|
|
47
|
-
operationId: currentPath?.operationId
|
|
47
|
+
operationId: currentPath?.operationId?.includes(pathname)
|
|
48
|
+
? "login"
|
|
49
|
+
: currentPath?.operationId,
|
|
48
50
|
requestBody: currentPath?.requestBody || {
|
|
49
51
|
description: "User credentials",
|
|
50
52
|
required: true,
|
|
@@ -95,7 +97,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
|
|
|
95
97
|
? "Logout from the system"
|
|
96
98
|
: currentPath?.summary,
|
|
97
99
|
description: currentPath?.description || "Invalidates the current user's JWT token",
|
|
98
|
-
operationId: currentPath?.operationId
|
|
100
|
+
operationId: currentPath?.operationId?.includes(pathname)
|
|
101
|
+
? "logout"
|
|
102
|
+
: currentPath?.operationId,
|
|
99
103
|
security: [{ BearerAuth: [] }],
|
|
100
104
|
responses: {
|
|
101
105
|
...(currentPath?.responses || {}),
|
|
@@ -122,7 +126,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
|
|
|
122
126
|
? "Register a new user"
|
|
123
127
|
: currentPath?.summary,
|
|
124
128
|
description: currentPath?.description || "Creates a new user account",
|
|
125
|
-
operationId: currentPath?.operationId
|
|
129
|
+
operationId: currentPath?.operationId?.includes(pathname)
|
|
130
|
+
? "signup"
|
|
131
|
+
: currentPath?.operationId,
|
|
126
132
|
requestBody: currentPath?.requestBody || {
|
|
127
133
|
description: "User registration data",
|
|
128
134
|
required: true,
|
|
@@ -169,7 +175,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
|
|
|
169
175
|
: currentPath?.summary,
|
|
170
176
|
description: currentPath?.description ||
|
|
171
177
|
"Changes the password for the authenticated user",
|
|
172
|
-
operationId: currentPath?.operationId
|
|
178
|
+
operationId: currentPath?.operationId?.includes(pathname)
|
|
179
|
+
? "updatePassword"
|
|
180
|
+
: currentPath?.operationId,
|
|
173
181
|
security: [{ BearerAuth: [] }],
|
|
174
182
|
requestBody: currentPath?.requestBody || {
|
|
175
183
|
description: "Current and new password",
|
|
@@ -227,7 +235,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
|
|
|
227
235
|
: currentPath?.summary,
|
|
228
236
|
description: currentPath?.description ||
|
|
229
237
|
"Retrieves information about the currently authenticated user",
|
|
230
|
-
operationId: currentPath?.operationId
|
|
238
|
+
operationId: currentPath?.operationId?.includes(pathname)
|
|
239
|
+
? "getMe"
|
|
240
|
+
: currentPath?.operationId,
|
|
231
241
|
security: [{ BearerAuth: [] }],
|
|
232
242
|
responses: {
|
|
233
243
|
...(currentPath?.responses || {}),
|
|
@@ -262,7 +272,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
|
|
|
262
272
|
: currentPath?.summary,
|
|
263
273
|
description: currentPath?.description ||
|
|
264
274
|
"Updates information for the currently authenticated user",
|
|
265
|
-
operationId: currentPath?.operationId
|
|
275
|
+
operationId: currentPath?.operationId?.includes(pathname)
|
|
276
|
+
? "updateMe"
|
|
277
|
+
: currentPath?.operationId,
|
|
266
278
|
security: [{ BearerAuth: [] }],
|
|
267
279
|
requestBody: currentPath?.requestBody || {
|
|
268
280
|
description: "User data to update",
|
|
@@ -309,7 +321,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
|
|
|
309
321
|
: currentPath?.summary,
|
|
310
322
|
description: currentPath?.description ||
|
|
311
323
|
"Marks the current user's account as deleted",
|
|
312
|
-
operationId: currentPath?.operationId
|
|
324
|
+
operationId: currentPath?.operationId?.includes(pathname)
|
|
325
|
+
? "deleteMe"
|
|
326
|
+
: currentPath?.operationId,
|
|
313
327
|
security: [{ BearerAuth: [] }],
|
|
314
328
|
responses: {
|
|
315
329
|
...(currentPath?.responses || {}),
|
|
@@ -348,7 +362,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
|
|
|
348
362
|
: currentPath?.summary,
|
|
349
363
|
description: currentPath?.description ||
|
|
350
364
|
"Retrieves a list of all available authentication actions and permissions",
|
|
351
|
-
operationId: currentPath?.operationId
|
|
365
|
+
operationId: currentPath?.operationId?.includes(pathname)
|
|
366
|
+
? "findManyAuthAction"
|
|
367
|
+
: currentPath?.operationId,
|
|
352
368
|
security: [{ BearerAuth: [] }],
|
|
353
369
|
responses: {
|
|
354
370
|
...(currentPath?.responses || {}),
|
|
@@ -415,7 +431,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
|
|
|
415
431
|
: currentPath?.summary,
|
|
416
432
|
description: currentPath?.description ||
|
|
417
433
|
"Retrieves all authentication actions for a specific resource",
|
|
418
|
-
operationId: currentPath?.operationId
|
|
434
|
+
operationId: currentPath?.operationId?.includes(pathname)
|
|
435
|
+
? "findOneAuthAction"
|
|
436
|
+
: currentPath?.operationId,
|
|
419
437
|
security: [{ BearerAuth: [] }],
|
|
420
438
|
parameters: mergedParameters,
|
|
421
439
|
responses: {
|