Skip to content

Instantly share code, notes, and snippets.

@secmohammed
Created August 11, 2019 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save secmohammed/4238c22909e400b22924878257d5cc3e to your computer and use it in GitHub Desktop.
Save secmohammed/4238c22909e400b22924878257d5cc3e to your computer and use it in GitHub Desktop.
type-graphql validating inputs using yup instead of class-validator
```
export const formatYupError = (err: ValidationError) => {
const errors: Array<{ path: string; message: string }> = [];
err.inner.forEach(e => {
errors.push({
path: e.path,
message: e.message
});
});
return errors;
};
```
```
const validationSchema = yup.object().shape({
email: yup
.string()
.min(3, emailNotLongEnough)
.max(255)
.email(invalidEmail)
.required(),
password: yup
.string()
.min(3, passwordNotLongEnough)
.max(255)
.required(),
firstName: yup
.string()
.trim()
.required()
.min(2, "First name is too short"),
lastName: yup
.string()
.trim()
.required()
.min(2, "Last name is too short")
});
// and inside the mutation's body
try {
await validationSchema.validate(
{
email,
firstName,
lastName,
password
},
{ abortEarly: false }
);
} catch (error) {
throw new UserInputError(
"Failed due to validation errors.",
formatYupError(error)
);
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment