forked from Bitcoindefi/OpenAO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-errors.ts
More file actions
173 lines (141 loc) · 4.73 KB
/
Copy pathapi-errors.ts
File metadata and controls
173 lines (141 loc) · 4.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
type ValidationIssue = {
code?: string;
path?: Array<string | number>;
message?: string;
origin?: string;
format?: string;
minimum?: number;
maximum?: number;
inclusive?: boolean;
validation?: string;
received?: string;
};
type ApiErrorLike = {
error?: unknown;
message?: unknown;
};
const FIELD_LABELS: Record<string, string> = {
name: "El nombre",
email: "El email",
identifier: "El email o nombre de usuario",
password: "La password",
capacity: "La capacidad",
characterId: "El personaje",
templateId: "La plantilla",
class: "La clase",
race: "La raza",
gender: "El genero",
headId: "La cabeza",
};
function getFieldLabel(path: ValidationIssue["path"]): string {
const firstSegment = path?.find((segment) => typeof segment === "string");
if (!firstSegment) {
return "El valor";
}
return FIELD_LABELS[firstSegment] ?? `El campo ${firstSegment}`;
}
function formatValidationIssue(issue: ValidationIssue): string {
const fieldLabel = getFieldLabel(issue.path);
switch (issue.code) {
case "too_small":
if (issue.origin === "string" && typeof issue.minimum === "number") {
return `${fieldLabel} debe tener al menos ${issue.minimum} caracteres.`;
}
return `${fieldLabel} es demasiado corto.`;
case "too_big":
if (issue.origin === "string" && typeof issue.maximum === "number") {
return `${fieldLabel} debe tener como maximo ${issue.maximum} caracteres.`;
}
return `${fieldLabel} es demasiado largo.`;
case "invalid_string":
case "invalid_format":
if (issue.validation === "email" || issue.format === "email") {
return "Ingresa un email valido.";
}
return `${fieldLabel} no es valido.`;
case "invalid_type":
if (issue.received === "undefined") {
return `${fieldLabel} es obligatorio.`;
}
return `${fieldLabel} no es valido.`;
case "invalid_enum_value":
return `${fieldLabel} no es valido.`;
case "custom":
return typeof issue.message === "string" && issue.message.trim()
? issue.message.trim()
: `${fieldLabel} no es valido.`;
default:
return typeof issue.message === "string" && issue.message.trim()
? issue.message.trim()
: `${fieldLabel} no es valido.`;
}
}
function tryParseJson(value: string): unknown {
const trimmed = value.trim();
if (!trimmed.startsWith("[") && !trimmed.startsWith("{")) {
return null;
}
try {
return JSON.parse(trimmed);
} catch {
return null;
}
}
function normalizePlainError(message: string): string {
const trimmed = message.trim();
switch (trimmed) {
case "Unauthorized":
return "Tu sesion no es valida o ya vencio.";
case "Unexpected error":
return "Ocurrio un error inesperado. Intenta de nuevo.";
default:
return trimmed;
}
}
function extractValidationIssues(value: unknown): ValidationIssue[] | null {
if (Array.isArray(value)) {
return value;
}
if (value && typeof value === "object" && Array.isArray((value as { issues?: unknown }).issues)) {
return (value as { issues: ValidationIssue[] }).issues;
}
return null;
}
export function toUserFriendlyError(input: unknown): string {
if (typeof input === "string") {
const parsed = tryParseJson(input);
if (parsed !== null) {
return toUserFriendlyError(parsed);
}
return normalizePlainError(input);
}
const issues = extractValidationIssues(input);
if (issues?.length) {
const messages = Array.from(
new Set(issues.map((issue) => formatValidationIssue(issue)).filter(Boolean)),
);
if (messages.length > 0) {
return messages.join(" ");
}
}
if (input && typeof input === "object") {
const payload = input as ApiErrorLike;
if (typeof payload.error === "string") {
return toUserFriendlyError(payload.error);
}
if (typeof payload.message === "string") {
return toUserFriendlyError(payload.message);
}
}
return "Ocurrio un error inesperado. Intenta de nuevo.";
}
export function normalizeErrorPayload<T>(payload: T): T {
if (!payload || typeof payload !== "object" || !("error" in payload)) {
return payload;
}
const nextPayload = payload as T & { error?: unknown };
return {
...nextPayload,
error: toUserFriendlyError(nextPayload.error),
};
}