Mutations in GraphQL - take 2

Last time we looked into GraphQL mutations, we tried a very simple one. This time we’ll see how to define a mutation with arguments and multiple objects returned.

A real life mutation in GraphQL will have multiple arguments and will return one or more objects.

GraphQL schema definition for a mutation

Here is such a mutation - AddPlayList:

let mutationType = new GraphQLObjectType({
  name: 'RootMutationType',
  fields: {
    AddPlayList: {
      description: 'Add a playlist for a given user',
      type: new GraphQLObjectType({
        name: 'AddPlayListInput',
        fields: () => ({
          playList : { type: PlayListType },
          user : { type: UserType }
        })
      }),
      args: {
        userId : { type: new GraphQLNonNull(GraphQLString) },
        title : { type: new GraphQLNonNull(GraphQLString) },
        description : { type: GraphQLString }
      },
      resolve: (parent, args, ast) => {
      }
    },
    updateCount: {
      type: GraphQLInt,
      description: 'Updates the count',
      resolve: function() {
        count += 1;
        return count;
      }
    }
  }
});

In this definition:

How to call a GraphQL mutation?

Here is the request to invoke such a mutation :

mutation test {
  AddPlayList(userId: "A", title: "the title", description: "the desc") {
    playList  {
        id
      title
    }
    user {
      id
      name
    }
  }
}

resolve() function for a mutation request

Let’s assume that the parameters to the resolve method are the same as for a query (see related post):

resolve: (parent, args, ast) => {
  console.log('resolve for Mutation of AddPlayList:');
  console.log('- parent:' + require('util').inspect(parent, { showHidden: false, depth: null }));
  console.log('-   args:' + require('util').inspect(args  , { showHidden: false, depth: null }));
  console.log("@@@ listOfFieldsFromSelectionSet:", listOfFieldsFromSelectionSet(ast.fieldASTs[0].selectionSet, ast.fragments));
}

We get this result:

- parent:{ message: 'hello world!' }
-   args:{ userId: 'A', title: 'the title', description: 'the desc' }
@@@ listOfFieldsFromSelectionSet: [ 'playList', 'user' ]

You would have to parse the selectionSet for playList and user to know which fields to bring back in the response.