8

I just want to get a gauge of what people think is the best practice for doing validation of user input fileds (such as url or email address) on the server with a graphql / orm setup.

My application is using apollo server / gql and sequelize as the orm.

I've seen some who do validation on the model in sequelize and other examples of validation in the graphql resolver with with a validation library or using custom scalars.

Is any one way preferable? Thanks.

jspru
  • 1,060
  • 1
  • 9
  • 17

1 Answers1

3

Input validation is some kind of AOP, like authentication and authorization. From my knowledge, there are five ways can do this.

  • Validation in resolver with the general approach, e.g. if (validationPass) {...} else {..} - Too verbose, keep the resolver thin is a best practice. Because It's some kind of route layer. Not recommend
  • Validation in resolver using a composition library, e.g. graphql-resolvers - Recommend
  • Validation in the model layer (ORM) using some decorators or model schema definition. - This is the traditional effective way no matter you use GraphQL, gRPC, soap WSDL, RESTful API. From the classic MVC software development idea. Recommend
  • Validation in GraphQL schema directive - A little complex, not recommend
  • Validation in GraphQL middleware - A little complex, you need to design the middleware and map the validation rules to the corresponding Query and Mutation, you quite possibly need to use the info parameter to get the GraphQL operation. Not recommend
Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • thanks for the overview. i ended up doing it in the model layer since it was already supported by Sequelize. – jspru Jan 21 '20 at 18:56