Friday, May 28, 2021

to change data in the queries, use mutations

 Instead of query, use mutation.


query for reading data, mutation is for modifying data.


In the schema file, add below code.


const mutation = new GraphQLObjectType({
  name: 'Mutation',
  fields: {
    addUser: {
      type: UserType,
      args: {
        firstName: {type: new GraphQLNonNull(GraphQLString)},
        age: {type: new GraphQLNonNull(GraphQLInt)},
        companyId:{type: GraphQLString}
      },
      resolve(parentValue,{firstName,age}){
        return axios.post('http://localhost:3000/users',{firstName,age})
        .then(res=>res.data);
      }
    }
  }
});

module.exports = new GraphQLSchema({
  query: RootQuery,//created for queries
  mutation//mutation: mutation
});

Now, to run in graphQL UI, use the mutation keyword as below.
The exclamation symbols before fields in the docs section refers as mandatory fields.

//graphql
mutation {
  addUser(firstName"Stephen",age26){
    id
    firstName
    age
  }
}

No comments:

Post a Comment