how do I create validation rules from a GraphQL schema

Viewed 810

How can I transform a simple GraphQL schema, which I can access server-side by importing and client-side by querying, into validation rules?

I can kind of see how I could do this for enums, lets say I have a title:

  enum Title {
    Mr, Ms, Mrs, Dr
  }

I could access the possible values by querying

  __type (name: "Title") {
    name
    enumValues {
      name
    }
  }

And now I can create a drop-down on the client or a validation on the server, but how do I encode and access for example the min/max length of a string field? Or min/max value for a number?

Do I need to add a custom type for each field? Or is, there a better way?


[edit] in response to Daniel's answer:

I'm using yup for validation, which is a great library, but for example if a certain field was required on a gql InputType, how do I get that into the yup schema?

And how do I use that yup schema on the front-end? Ideally I would like to serialise it, send it to the client, and reconstruct the validation there.

The only other way I can think of is to share the code, but then I need to re-build and re-deploy the client each time the schema changes, which is of course out of the question :/

1 Answers

There are a number of kinds of data validation, for example:

  • Data type (is this value a string or number?)
  • Range (is this value within this range of values?)
  • Constraint (does this value satisfy this regex expression?)
  • Consistency (is the end date after the start date?)
  • Referential (does the provided identifier reference an entity that actually exists?)

Strongly typed languages like GraphQL can only really provide data type validation. Your GraphQL service may perform other kinds of validation (through your data source, your data models, custom GraphQL scalars, etc.) -- however, only type information can be introspected from the service. Introspection is not the appropriate tool for communicating other validation logic to your client.

If you're using Node.js on the backend and your intent is to share validation logic between your backend and your frontend, then the best approach would be to utilize a library like yup or joi.

Related