graphql - Apollo GraphQL 服务器中的突变调用有什么问题?
问题描述
来电:
mutation {
upvotePost(postId: 1) {
id
}
}
代码下方:
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = `
type Author {
id: Int!
firstName: String
lastName: String
"""
the list of Posts by this author
"""
posts: [Post]
}
type Post {
id: Int!
title: String
author: Author
votes: Int
}
# the schema allows the following query:
type Query {
posts: [Post]
author(id: Int!): Author
}
# this schema allows the following mutation:
type Mutation {
upvotePost (
postId: Int!
): Post
}
`;
// example data
const authors = [
{ id: 1, firstName: 'Tom', lastName: 'Coleman' },
{ id: 2, firstName: 'Sashko', lastName: 'Stubailo' },
{ id: 3, firstName: 'Mikhail', lastName: 'Novikov' },
];
const posts = [
{ id: 1, authorId: 1, title: 'Introduction to GraphQL', votes: 2 },
{ id: 2, authorId: 2, title: 'Welcome to Meteor', votes: 3 },
{ id: 3, authorId: 2, title: 'Advanced GraphQL', votes: 1 },
{ id: 4, authorId: 3, title: 'Launchpad is Cool', votes: 7 },
];
const resolvers = {
Query: {
posts: () => posts,
author: (_, { id }) => find(authors, { id }),
},
Mutation: {
upvotePost: (_, { postId }) => {
const post = find(posts, { id: postId });
if (!post) {
throw new Error(`Couldn't find post with id ${postId}`);
}
post.votes += 1;
return post;
},
},
Author: {
posts: author => filter(posts, { authorId: author.id }),
},
Post: {
author: post => find(authors, { id: post.authorId }),
},
};
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({ typeDefs, resolvers });
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(` Server ready at ${url}`);
});
解决方案
为了使用“查找”方法,您需要导入 lodash
npm install lodash
然后在你的文件中需要像这样的lodash:
const { find, filter } = require('lodash');
推荐阅读
- c# - 无论选项卡标题如何,如何更改导航栏标题
- linux-device-driver - UART驱动程序中的“启动”功能可以知道Linux中打开了哪个tty设备(例如“ttyUSB0”)吗?
- javascript - 访问自定义角度 HTML 标记的 nativeElement
- java - 如何在 Spring Boot 中访问非主 DataSource?
- jquery - jQuery PNotify 按钮单击多次触发
- oracle - Oracle 高级队列
- django - Python按月将列表拆分为各种列表
- mysql - 使用 StreamSets 从 Kafka 消费者向 MySQL 写入数据
- python - 使用python脚本连接到mysql数据库
- html - 我可以使用以下代码(html、css)使我的网站与 RTL 兼容吗?