Created
August 11, 2019 12:19
-
-
Save secmohammed/4238c22909e400b22924878257d5cc3e to your computer and use it in GitHub Desktop.
type-graphql validating inputs using yup instead of class-validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
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; | |
}; | |
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
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