Change Graphql Mutation Response with Interface type Apollo and Yoga

Interfaces are a powerful way to build and use GraphQL schemas through the use of abstract types. Abstract types can’t be used directly in schema, but can be used as building blocks for creating explicit types.

Here we are using Graphql Interface type to change Mutation response to include success and message on every mutation response. So that we can identify whether mutation is completely success or not.

First create graphql interface we want

const Query = `
  interface MutationResponse {
    code: Int!
    success: Boolean!
    message: String!
  }
`;
  1. Creating the type post used to return
  2. Then create another type called “UpdatePostMutationResponse” with extra field required by implementing common interface with post.

You may be wonder why we have included the duplicated fields on interface type. Every time you implement a inteface in graphql you have to define those fields again if not graphql will pass validation error.

const Query = `
  # posts
  type Post{
    title: String
    body: String
  }

  type UpdatePostMutationResponse implements MutationResponse {
    code: Int!
    success: Boolean!
    message: String!
    post: Post
  }

  interface MutationResponse {
    code: Int!
    success: Boolean!
    message: String!
  }
`;

Now add our custom mutation response type to mutation

//Merging schemas or queries
const Query = `
  type Query {
    
  }
  type Mutation {
    updatePost(id:ID!,title:String!) : UpdatePostMutationResponse
  }

  type UpdatePostMutationResponse implements MutationResponse {
    code: Int!
    success: Boolean!
    message: String!
    post: Post
  }

  interface MutationResponse {
    code: Int!
    success: Boolean!
    message: String!
  }
`;

Once you run above example you may receive below error.

Type “MutationResponse” is missing a “__resolveType” resolver. Pass false into “resolverValidationOptions.requireResolversForResolveType” to disable this warning.

or

Type ******  is missing a “__resolveType” resolver. Pass false into “resolverValidationOptions.requireResolversForResolveType” to disable this warning.

This is because of the new interface type you added to graphql schema. Once you add new inteface type make sure to include below function to resolvers.

  MutationResponse: {
    __resolveType(mutationResponse, context, info){
      return null;
    },
  },

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
mike
Guest
mike

Very energetic post, I enjoyed that a lot. Will there be a part 2?