如何在Octokit GraphQL中避免指定字段名?
问题
我的GraphQL mutation查询如下:
mutation prrt($input: AddPullRequestReviewThreadInput!) { addPullRequestReviewThread(input: $input) { thread { id } } }
使用Octokit时,我需要这样写代码:
const mutateFn = graphql<{ addPullRequestReviewThread: AddPullRequestReviewThreadPayload; }>; const response = await mutateFn(mutation, { input, headers });
其中addPullRequestReviewThread: 这段内容太冗长了,有没有办法自动推断?我只想指定Payload类型AddPullRequestReviewThreadPayload。这是所有GraphQL都要求的吗?
回答
Octokit的GraphQL客户端要求明确顶层字段的类型映射,这是因为GraphQL响应的结构完全对应你查询的顶层字段——你查的是addPullRequestReviewThread,响应对象里就必然有这个键,TypeScript需要明确这个映射关系。这不是GraphQL本身的强制要求,而是Octokit类型系统的设计。
不过可以通过几种方式简化:
复用TypeScript工具类型
定义一个通用的响应结构类型,把Payload类型作为泛型参数传入,不用每次手动写顶层字段名:type MutationResponse<T> = { addPullRequestReviewThread: T; }; const mutateFn = graphql<MutationResponse<AddPullRequestReviewThreadPayload>>;如果有其他同结构的mutation,直接替换泛型参数即可。
封装通用创建函数
写一个工具函数自动生成带类型的mutate函数,把顶层字段名作为参数传入:function createMutateFn<T>(fieldName: string) { return graphql<{ [K in typeof fieldName]: T }>; } // 使用示例 const mutateFn = createMutateFn<AddPullRequestReviewThreadPayload>('addPullRequestReviewThread');代码生成工具(彻底解决)
用@graphql-codegen/cli这类工具,配合对应插件可以根据你的GraphQL查询自动生成完整的TypeScript类型和Octokit调用代码,完全不用手动维护类型映射。工具会解析你的查询字符串,自动关联顶层字段和对应的Payload类型。
内容的提问来源于stack exchange,提问作者Minh Nghĩa
相关产品推荐
相关产品推荐

