如何使用 GraphQL Playground 在 ApolloServer 中运行突变?

问题描述

我正在使用 node.js、express 和 apollo-server-express。使用以下代码

string p;
getline(cin,p);
int n;
cin>>n;
vector <string> v(n);
int meet=meetTime(p);
cout<<p<<endl;
for(int i=0;i<n;i++){
    string s;
    getline(cin,s);
    //11:59 AM 12:00 PM
    v[i]=s;
}

当我在 GraphQL Playground 中输入突变时,如下所示:

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}`)
);

我收到以下错误:“无法在“查询”类型上查询字段“change_title”。”

我的目标是能够运行突变。如果我应该以另一种方式做,或者如果有错误,请告诉我。谢谢!

解决方法

GraphQL playground 将所有类型都视为查询,除非另有说明。

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