下面是我最简单的graphQL服务器,但问题-我无法访问在查询中传递的过滤器参数
const { ApolloServer, gql } = require('apollo-server')
const { makeExecutableSchema } = require('graphql-tools')
const { buildSchema } = require('graphql')
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
genre: 'Fantasy',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
genre: 'General fiction',
},
]
const typeDefs = gql`
type Book {
title: String
author: String
genre: String,
}
type Query {
books(filter: String): [Book]
}
`
const resolvers = {
Query: {
books: (filter) => {
console.info('resolvers: ', { books, filter })
const { filter } = arg2
const booksFiltered = books.filter(item => item.genre === filter)
return booksFiltered
},
},
}
const schema = makeExecutableSchema({
typeDefs,
resolvers,
})
const server = new ApolloServer({ schema })
server.listen().then(({ url }) => {
console.log(` Server ready at ${url}`)
})
我的查询:
{
books(filter: "Fantasy") {
title,
author,
genre,
}
}
出了什么问题?为什么我在console.info中有filter === undefined
?
答案 0 :(得分:0)
经过一些耗时的测试,结果发现解决方案是从第二个参数(在本例中为args
)中获取参数作为属性之一:
...
const resolvers = {
Query: {
books: (parent, args, context, info) => {
console.info('resolvers: ', { books, args })
const { filter } = args
const booksFiltered = books.filter(item => item.genre === filter)
return booksFiltered
},
},
}
...
解析器函数采用四个参数(按此顺序):