MERN Stack & GraphQL - #7 Server-Side Validation
Welcome back to the series! In this episode, we'll discuss an important topic of server-side validation in web APIs. Although our discussion will be centered around GraphQL, you'll find that the same exact principles also apply to Node.js apps at large.
As with many things in web development, there is more than one way to go about input validation. To have a broader picture of the landscape, we're going to take a sneak peek at several approaches, as well as compare and contrast the ups and downs of each.
What I envision for GraphQL APIs is that validation will be handled as part of the schema definition. It may or may not come true, but for the moment, there is one emerging library out there that attempts to bring this idea to life https://github.com/confuser/graphql-constraint-directive It works by declaring a @constraint directive that can be applied on input type fields. The library was also showcased in the Apollo blog https://blog.apollographql.com/graphql-validation-using-directives-4908fd5c1055 though only for v1. It's a shame that it doesn't work with v2 yet.
If validation is not feasible in the schema, then the next logical place would be in resolvers. Apollo v2 ships with built-in exceptions https://www.apollographql.com/docs/apollo-server/features/errors.html that we can raise, as soon as we find that the input is flawed. If-else checks tend to recur across resolvers though making it hard to keep the code DRY.
The next step forward would be to extract out validation checks into pure functions. We could then group them as part of a utils module, and cherry-pick them on demand. This would be a perfect time to pull in a helper library, such as validator.js https://www.npmjs.com/package/validator which comes with handy functions for verifying emails, phone numbers, object IDs, etc. It might still feel odd that we're rolling out our own custom validation though.
Another approach would be to use the built-in validators in Mongoose https://mongoosejs.com/docs/validation.html Similar to many other ODMs and ORMs, Mongoose has our back with standard validators for strings, numbers, dates, etc. Useful as they are, they often fall short with complex checks, so you might often need more granular control over validation. That's where custom validators come in. Support for customized error messages is available as well.
One could argue that validation shouldn't be a concern to the data models. In that case, we have a vast array of validation packages on NPM to choose from. One of the most mature and loved ones is joi https://www.npmjs.com/package/joi Joi has evolved over the years, and now features an extensive API for just about every use case you might run into. Chances are, what you're trying to achieve with joi, someone has already done before, so you only need to find the right issue in their GitHub repo.
Joi might also stun you with its rich and expressive API. (The only other validation API I'd compare it to is the one in Laravel, which is just as versatile and joyful) One minor disappointment with the library is its cryptic error messages, but luckily, it lets us customize those as well. As I can't think of any better solution for Node.js, I'd say we go with joi for this series. What do you guys think?
In the next video, we'll wire up joi to our resolvers, and I will also demonstrate how we can leverage validation both in Joi and Mongoose.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «MERN Stack & GraphQL - #7 Server-Side Validation», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.