In preparation for supporting comments on our blog, let’s create users. We’re building a modern mobile first blog of course, and thus want to support either a phone number or an email as the contact method for a user.
We want to support the following mutations.
To do this we need the ability to create nested arguments. GraphQL has InputObjects for this purpose. InputObjects are key value pairs just like regular Objects, but designed for input (you can’t do circular references with them for example).
Another notion we’ll look at here is an Enum type. We only want to support contact
"phone" at the moment, and GraphQL gives us the ability to
specify this in our schema.
Let’s start with our contact_type Enum.
Easy! Now if a user tries to send some other kind of contact type they’ll get a nice error without any extra effort on your part. Enum types are not a substitute for modeling layer validations however, be sure to still enforce things like this on that layer too.
Now for our contact input object.
Note that we name this type
:contact_input. We may also want a regular
object and types share a global namespace. In general it often makes sense to
suffix your input object type names with
Finally our schema:
Suppose in our database that we store contact information in a different database table. Our resolver would be used to create both rows in this case.
There does not need to be a one to one correspondence between how data is structured in your underlying data store and how things are presented by your GraphQL api.
Our resolver might look something like this:
Next: Read "Conclusion"