eletrotupi / tcc/ commit / fa665bd

frontend: translate zod error messages

Pedro Lucas Porcellis porcellis@eletrotupi.com · 4 months ago fa665bdbab7d637d3dccb1a31808acb9611fb861 Browse files
Parents 4afa669
Changed files
1
Additions
+44
Deletions
0
/dev/null → frontend/lib/errors/translations.ts
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 +
};
13 +

14 +
const PATTERN_MAP: Array<[RegExp, string | ((m: RegExpMatchArray) => string)]> = [
15 +
  [/String must contain at least (\d+) character\(s\)/, (m) => `Deve ter pelo menos ${m[1]} caractere(s)`],
16 +
  [/String must contain at most (\d+) character\(s\)/, (m) => `Deve ter no máximo ${m[1]} caractere(s)`],
17 +
  [/Number must be greater than or equal to ([\d.]+)/, (m) => `Deve ser maior ou igual a ${m[1]}`],
18 +
  [/Number must be less than or equal to ([\d.]+)/, (m) => `Deve ser menor ou igual a ${m[1]}`],
19 +
  [/Expected (\w+), received (\w+)/, () => 'Tipo de valor inválido'],
20 +
  [/Invalid enum value/, () => 'Opção inválida'],
21 +
  [/Validation error:/, () => 'Erro de validação'],
22 +
  [/^HTTP \d+$/, () => 'Algo deu errado. Tente novamente.'],
23 +
];
24 +

25 +
export function translateError(message: string): string {
26 +
  if (MESSAGE_MAP[message]) return MESSAGE_MAP[message];
27 +

28 +
  for (const [pattern, replacement] of PATTERN_MAP) {
29 +
    const match = message.match(pattern);
30 +
    if (match) {
31 +
      return typeof replacement === 'function' ? replacement(match) : replacement;
32 +
    }
33 +
  }
34 +

35 +
  return message;
36 +
}
37 +

38 +
export function translateFields(
39 +
  fields: Record<string, string>,
40 +
): Record<string, string> {
41 +
  return Object.fromEntries(
42 +
    Object.entries(fields).map(([k, v]) => [k, translateError(v)]),
43 +
  );
44 +
}