| 1 | const MESSAGE_MAP: Record<string, string> = {
|
| 2 | 'Required': 'Campo obrigatório',
|
| 3 | 'Invalid email': 'Email inválido',
|
| 4 | 'Invalid email address': 'Email inválido',
|
| 5 | 'Invalid credentials': 'Credenciais inválidas',
|
| 6 | 'Record not found': 'Registro não encontrado',
|
| 7 | 'Unique constraint violation': 'Email já cadastrado',
|
| 8 | 'Network error': 'Erro de conexão',
|
| 9 | 'Internal server error': 'Erro interno. Tente novamente.',
|
| 10 | 'Invalid or expired token': 'Link inválido ou expirado',
|
| 11 | 'No token provided': 'Sessão inválida',
|
| 12 | 'periodEnd must be after periodStart and range ≤ 90 days': 'O período deve ter entre 1 e 90 dias',
|
| 13 | };
|
| 14 |
|
| 15 | const PATTERN_MAP: Array<[RegExp, string | ((m: RegExpMatchArray) => string)]> = [
|
| 16 | [/String must contain at least (\d+) character\(s\)/, (m) => `Deve ter pelo menos ${m[1]} caractere(s)`],
|
| 17 | [/String must contain at most (\d+) character\(s\)/, (m) => `Deve ter no máximo ${m[1]} caractere(s)`],
|
| 18 | [/Number must be greater than or equal to ([\d.]+)/, (m) => `Deve ser maior ou igual a ${m[1]}`],
|
| 19 | [/Number must be less than or equal to ([\d.]+)/, (m) => `Deve ser menor ou igual a ${m[1]}`],
|
| 20 | [/Expected (\w+), received (\w+)/, () => 'Tipo de valor inválido'],
|
| 21 | [/Invalid enum value/, () => 'Opção inválida'],
|
| 22 | [/Validation error:/, () => 'Erro de validação'],
|
| 23 | [/^HTTP \d+$/, () => 'Algo deu errado. Tente novamente.'],
|
| 24 | ];
|
| 25 |
|
| 26 | export function translateError(message: unknown): string {
|
| 27 | const text = message instanceof Error ? message.message : String(message);
|
| 28 |
|
| 29 | if (MESSAGE_MAP[text]) return MESSAGE_MAP[text];
|
| 30 |
|
| 31 | console.log("Erro foi: ", text)
|
| 32 |
|
| 33 | for (const [pattern, replacement] of PATTERN_MAP) {
|
| 34 | const match = text.match(pattern);
|
| 35 | if (match) {
|
| 36 | return typeof replacement === 'function' ? replacement(match) : replacement;
|
| 37 | }
|
| 38 | }
|
| 39 |
|
| 40 | return text;
|
| 41 | }
|
| 42 |
|
| 43 | export function translateFields(
|
| 44 | fields: Record<string, string>,
|
| 45 | ): Record<string, string> {
|
| 46 | return Object.fromEntries(
|
| 47 | Object.entries(fields).map(([k, v]) => [k, translateError(v)]),
|
| 48 | );
|
| 49 | }
|