We can make GraphQL Types and mutations DRY using interfaces. An Interface is an abstract type that contains a collection of types which implement some of the same fields. We can avoid specifying the same set of fields in different GraphQL Types and mutations by defining an interface and using in sharing Types and mutations.
Interfaces can have fields, defined with a field, just like a GraphQL object type. Objects which implement this field inherit field definitions from the interface. An object type can override the inherited definition by redefining that field.
For example, active record time stamps are common fields in Rails models. So we can avoid declaring these fields in all object types by declaring an interface ActiveRecordTimestamp with these fields and using it our object types.
Example for including multiple interfaces in Ruby object type.
app/graphql/types/comment_type.rb
123456789
CommentType=GraphQL::ObjectType.definedoname"Comment"# multiple interfaces included using comma.interfaces[ActiveRecordTimestamp,GraphQL::Relay::Node.interface]field:id,types.Intfield:comment,types.Stringfield:user,UserTypeend
Now, this active record time stamp will be available in both above-mentioned object types.
We can use return_interfaces to define and reuse return types in different mutation definitions. The result of the resolve block will be passed to the field definitions in the interfaces, and both interface-specific and mutation-specific fields will be available to clients.
For example, we can define a interface which will define notification of a mutation.
# encoding: utf-8CreateArticle=GraphQL::Relay::Mutation.definedo# ...return_field:title,types.Stringreturn_field:body,types.Stringreturn_interfaces[MutationResult],# clientMutationId will also be available automaticallyresolve->(obj,input,ctx){article,notice=Article.create_with_input(...){success:article.persisted?notice:noticetitle:article.titleerrors:article.errors}}end