eletrotupi / tcc/ frontend/lib/errors/translations.tsf2e8f9009eea845da1d93f97d5e52c5d780b0f0e
1.9 KB | 47 lines Raw
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: string): string {
27
  if (MESSAGE_MAP[message]) return MESSAGE_MAP[message];
28

29
  console.log("Erro foi: ", message)
30

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

38
  return message;
39
}
40

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