如何从解析器函数访问字段参数?

时间:2019-05-03 03:41:37

标签: api graphql graphql-js

下面是我最简单的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

1 个答案:

答案 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
    },
  },
}
...

解析器函数采用四个参数(按此顺序):

  1. parent:上一个解析程序调用的结果(更多信息)。
  2. args:解析程序字段的参数。
  3. 上下文:每个解析器可以读取/写入的自定义对象。
  4. info:它包含查询AST和更多执行信息