eletrotupi / tcc/ frontend/lib/errors/translations.tsc901c35af9c84b6a29e5185545ced1129f33b8f4
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: unknown): string {
27
  const text = message instanceof Error ? message.message : String(message);
28

29
  if (MESSAGE_MAP[text]) return MESSAGE_MAP[text];
30

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

38
  return text;
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
}