如何利用@graphql-codegen生成的代码实现单条记录查询?
我已完成GraphQL Codegen的入门指南,基于已部署的联邦图生成了代码文件,其中包含:
export type Query = { __typename?: 'Query'; customerById: Customer; // not a complete list };
现在我想获取ID为5a5e5aca-5512-4fb7-bde4-03fadf88e777的客户,但官方文档要求编写新的GQL语句,示例如下:
const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ query allFilmsWithVariablesQuery($first: Int!) { allFilms(first: $first) { edges { node { ...FilmItem ... const { data } = useQuery(allFilmsWithVariablesQueryDocument, { variables: { first: 10 } })
这看起来需要手写本地GQL语句来查询远程联邦图,但我更希望能写出类似const customer = runQuery(Queries.customerById, {id: '5a5e5aca-5512-4fb7-bde4-03fadf88e777' })的代码——这种方式和Zeus的链式查询更接近,同时能获得查询时的自动补全功能。
Zeus虽然支持该功能,但存在全局fetch、全局Websocket这类奇怪依赖,且我不想修改生成的代码。请问GraphQL Codegen是否具备这种能力?如果可以通过Query:customerById实现查询,具体该怎么操作?
解答
GraphQL Codegen本身支持生成类似Zeus的链式查询客户端,不需要手写GQL语句,且能保留类型自动补全,同时可以自定义网络层(避免全局依赖问题)。具体操作步骤如下:
安装必要插件
安装基础客户端预设和类型化文档节点插件:npm install -D @graphql-codegen/client-preset @graphql-codegen/typed-document-node配置代码生成规则
在codegen.ts中启用链式查询相关配置,示例如下:import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { schema: '你的联邦图地址', documents: ['./src/**/*.tsx'], generates: { './src/gql/': { preset: 'client', plugins: ['typed-document-node'], presetConfig: { documentMode: 'string', persistedQueries: true, }, }, }, }; export default config;生成链式查询代码
运行代码生成命令后,会在指定目录生成包含类型安全查询函数的代码。你可以直接调用生成的查询函数,无需手写GQL:import { useQuery } from '@apollo/client'; import { customerByIdQuery } from './src/gql'; // 变量会自动补全类型提示 const { data } = useQuery(customerByIdQuery, { variables: { id: '5a5e5aca-5512-4fb7-bde4-03fadf88e777' }, });自定义网络层
你可以使用Apollo Client、Urql等成熟客户端来控制网络请求,完全避免全局依赖。例如用Apollo Client自定义链接:import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client'; const client = new ApolloClient({ link: new HttpLink({ uri: '你的联邦图地址' }), cache: new InMemoryCache(), });
关键说明
- 生成的
customerByIdQuery是完全类型安全的,变量和返回值都会有自动补全,符合你想要的直接调用查询字段的体验。 - 所有配置都通过代码生成文件完成,无需修改生成的代码,网络层由你自主控制,解决Zeus的全局依赖问题。
内容的提问来源于stack exchange,提问作者jcollum

