如何将嵌套的解析器添加到架构?

时间:2017-03-22 11:07:02

标签: apollo apollo-server

让我们说我的查询如下:

query {
  post {
    id
    user { id, name } 
  }
}

解析器地图如下所示:

{
  Query: {
    post: myPostResolverFunc,
  }
}

我如何添加额外的"嵌套" post.user的解析器? 我尝试了这个,但它不起作用:

addResolveFunctionsToSchema(schema, {
  Query: {
    post: {
      user: postUserResolveFunc,
    },
  }
});

1 个答案:

答案 0 :(得分:3)

你只需要为你的领域写一个解析器。假设您的架构是这样的:

type Post {
  id: ID!,
  user: User
}

type User {
  id: ID!,
  username: String!
}

type Query {
  post(id: ID!): Post  #assuming you want to request a simple post here
}

您可以像这样编写解析器:

addResolveFunctionsToSchema(schema, {
  Post: {
    user(root) {
      getUserById(root.user)
    }
  }
  Query: {
    post(root, args, context) {
      return getPostById(args.id)
    }
  }
});