首页 > 解决方案 > 带有数组参数的嵌套 GraphQL 查询

问题描述

我正在使用apollo-datasource-restapollo-server-lambda试图弄清楚如何将查询映射到特定的解析器。我有以下模式,其中plan查询应该返回用户列表(应该由users查询而不是user查询驱动)。

  type Query {
    user(user_id: String, username: String): User
    users(user_ids: [String!]): [User!]
    plan(plan_id: String): Plan
  }

  type User {
    id: String
    username: String
    first: String
    last: String
    image: String
  }

  type Plan {
    title: String
    image: String
    attending: [User]
  }

plan查询解析器数据源如下:

planReducer(data) {
  return {
    image: data.public.info.image,
    title: data.public.info.title,
    attending: Object.keys(data.public.attending)
  }
}

data.public.attendingplanReducer返回一个 s 数组,user_id然后我希望能够将其输入到我的users查询中,而不是我的user查询。

这些是我目前的解析器:

user: (_, { username }, { dataSources }) =>
  dataSources.userData.getUserByUsername({ username: username }),
users: async (_, { user_ids }, { dataSources }) => {
  const usersArray = await dataSources.userData.getUsersByIds({ userIds: user_ids })
  return usersArray
},
plan: async (_, { plan_id }, { dataSources }) => {
  return dataSources.planData.getPlanById({ planId: plan_id })
}

标签: graphqlapollo-server

解决方案


您的解析器映射应如下所示:

const resolvers = {
  Query: {
    plan: async (_parent, { plan_id: planId }, { dataSources }) => (
      dataSources.planData.getPlanById({ planId })
    )
  },
  Plan: {
    users: async ({ user_ids: userIds }, _variables, { dataSources }) => (
      dataSources.userData.getUsersByIds({ userIds })
    )
  }
}

其中的每个键都Query应该是一个解析器,对应于Query架构根中定义的查询。作为根的直接子级的键,在这种情况下,当从内的解析器Plan返回时,将用于解析它们对应的类型。planQuery

如果未定义解析器,GraphQL 将回退到默认解析器,在这种情况下,该解析器如下所示:

const resolvers = {
  Plan: {
    title: (parent) => parent.title,
    image: (parent) => parent.image,
  }
}

通过指定自定义解析器,您可以根据父解析器的返回值计算要返回给客户端的字段。


推荐阅读