在 TypeScript 中对 Apollo 中的非空字段使用默认解析器/类型解析器

问题描述 投票:0回答:1

我正在使用

@graphql-codegen/cli
通过 Apollo 创建 GraphQL API。解析器是用 TypeScript 编写的。我无法弄清楚如何使用默认解析器来解析不可为空的字段。问题是 TypeScript 似乎需要我为主解析器中的所有不可空字段提供值,这意味着默认解析器不会被使用。

我的 GraphQL:

type Post {
  id: ID!
  body: String!
}
input PostsRequest {
  start: Int
  end: Int
  cursor: Int
}

type PostsResponse {
  posts: [Post!]!
  totalCount: Int!
}

extend type Query {
  posts(request: PostsRequest!): PostsResponse!
}

PostsResponse 永远不会是

null
,它的任何一个字段也不会。我的解析器是这些:

export const PostsResolver: Resolvers<{ query: { value: number } }> = {
  Query: {
    posts: (_, { request: { start, end } }, context = { query: { value: 4 } }) => {
      const query = constructQuery(start ?? 0, end ?? 5);

      context.query = query;
      return {
        totalCount: -1,
        posts: [{ id: "-1", body: "you should never see this!" }],
      };
    },
  },
  PostsResponse: {
    posts: (_1, _2, context) => {
      const results = executeQuery(context.query);
      return results.map((result) => ({ id: result.id, body: "you should never see this!" }));
    },
    totalCount: (_1, _2, context) => executeCount(context.query),
  },
  Post: {
    body: (post) => getPostBody(post.id),
  },
};

这会返回“你永远不应该看到这个!”与所有帖子正文一样,而不是

getPostBody()
返回的内容。如何让默认解析器在上面的代码中执行?

typescript graphql apollo resolver codegen
1个回答
0
投票

这应该像删除线一样简单:

posts: [{ id: "-1", body: "you should never see this!" }],

由于

posts
解析器中缺少此内容,GraphQL 将在您的
PostResponse
解析器下寻找它。

© www.soinside.com 2019 - 2024. All rights reserved.