graphqlapollo-servergraphql-playground

How to run a mutation in ApolloServer using the GraphQL Playground?


I'm using node.js, express and apollo-server-express. With the following code:

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const typeDefs = gql`
  type Book { title: String author: String }
  type Query { books: [Book] }
  type Mutation { change_title(new_title: String): Book }
`;

const books = [
  { title: 'The Awakening', author: 'Kate Chopin', },
  { title: 'City of Glass', author: 'Paul Auster', },
];

const resolvers = {
  Query: { books: () => books, },
  Mutation: {
    change_title: (parent, args) => {
      books[0].title = args.new_title
      return books[0]
    }
  }
};

const server = new ApolloServer({ typeDefs, resolvers, });
const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
  console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)
);

When I enter the mutation in the GraphQL Playground, like so:

{
    change_title(new_title: "Something") {
    title
  }
}

I get the following error: "Cannot query field "change_title" on type "Query"."

My goal is to be able to run mutations. If I should be doing it another way or if there's eror, please let me know. Thanks!


Solution

  • GraphQL playground treats all types as queries unless otherwise specified.

    mutation {
        change_title(new_title: "Something") {
        title
      }
    }