【问题标题】:How to access fields arguments from the resolver function?如何从解析器函数访问字段参数?
【发布时间】:2019-09-21 14:22:13
【问题描述】:

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

【问题讨论】:

    标签: api graphql graphql-js


    【解决方案1】:

    经过一些耗时的测试,结果证明解决方案是从第二个参数(在本例中为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 和更多执行信息

    【讨论】:

      猜你喜欢
      • 2022-12-14
      • 2019-02-27
      • 2023-03-22
      • 2011-09-22
      • 2017-05-26
      • 2020-09-14
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多