mutationaddArticle{addArticle(input:{title:"GraphQL mutation",body:" This article is about graphql mutation using InputObjectType"}){article{idtitlebody}}}
For saving this we need to instantiate article object by assigning each and every input params like this.
This method become ugly if our object contain lots fields.
We can define and utilize mutation input params in the better way using InputObjectType. If we can specify article object as input_field instead of each field we can save object like below.
app/graphql/mutations/article_mutations.rb
1
article=Article.new(inputs[:article].to_h)
which is maintanable and easy to read.
Lets see how we can achive this.
The first step is to define InputObjectType and declare that input object type as input_field. Here we are going to create InputObjectType in another folder inside our graphql folder for maintainability.
Now we can declare ArticleInputObjectType as input_field inside our mutation and use declared input_field inside our mutation resolver to save the article. So final mutation definition will look like this.
That’s it, we are done, now we can save new article using addArticle mutation.
12345678910
mutationaddArticle{addArticle(input:{article:{title:"GraphQL mutation",body:" This article is about graphql mutation using InputObjectType"}}){article{idtitlebody}}}
If we want to map camel case arguments into DB fields which are in snake case, we can use as keyword.