Vyhledávání na webu

typescript - Jak vytvořit více vlastních chybových zpráv pomocí Typeboxu od Elysie?


Chci vytvořit schéma s Typeboxem od Elysia tak, aby se pro každou kontrolu zobrazila jiná chybová zpráva. Chci udělat něco podobného, co dělá Joi.

Joi :

import joi from 'joi';

export const CreateUserSchema = joi.object({
  name: joi.string().required().messages({
    'any.required': 'The name field is required.',
    'string.empty': 'The name field cannot be empty.',
  }),
  email: joi.string().email().required().messages({
    'any.required': 'The address field is required.',
    'string.email': 'The email field is invalid.',
    'string.empty': 'The address field cannot be empty.',
  }),
  password: joi.string().min(6).required().messages({
    'any.required': 'The password field is required.',
    'string.empty': 'The password field cannot be empty.',
    'string.min': 'The password field must have at least 6 characters.',
  }),
});

export type CreateUserDTO = {
  name: string;
  email: string;
  password: string;
};

Typebox od Elysia:

import { t, type Static } from "elysia"

export const CreateUserSchema = t.Object({
    name: t.String({
        minLength: 1,
        error: 'The name field cannot be empty.'
    }),
    email: t.String({
        format: 'email',
        error: 'The email provided is invalid.'
    }),
    password: t.String({
        minLength: 6,
        error: 'The password field cannot be less than 6 characters long.'
    })
})

export type CreateUserDTO = Static<typeof CreateUserSchema>

Toto je jednoduchý příklad, ale chci to aplikovat na parametry, které vyžadují více kontrol

Už jsem zkoušel použít pole nebo objekt uvnitř vlastnosti error typu typebox, ale jednoduše to nepřijímá.

Odpověď č. 1

Elysia přijímá funkci jako chybu, takže ji můžete používat takto

t.Object({
  name: t.String({
    minLength: 1,
    error({ errors, type, validator, value }) {
      const error = errors[0];
      switch (error.type) {
        case ValueErrorType.ObjectRequiredProperty: {
          return 'The name field is required.';
        }
        case ValueErrorType.StringMinLength: {
          return 'The name field cannot be empty.';
        }
        default: {
          return error.message;
        }
      }
    },
  }),
})