如何解决在 Graphql 中使用 RTK 查询
到目前为止,我明白我需要构建自己的 baseQuery
。我可以像这里https://rtk-query-docs.netlify.app/examples/react-with-graphql中的示例那样编写graphql查询和突变,如果我像这样query.builder
向builder.query<Device,void>
添加类型,或者我必须使用类似的东西,我是否可以获得查询和突变的完整类型安全这个https://www.graphql-code-generator.com/docs/plugins/typescript-graphql-request#simple-request-middleware。在后一种情况下,如果我为 graphql 请求库使用生成的钩子,我的 baseQuery
应该如何看。
以下是来自 2 的钩子示例:
import { GraphQLClient } from 'graphql-request';
import { getSdk } from './sdk'; // THIS FILE IS THE GENERATED FILE
async function main() {
const client = new GraphQLClient('https://countries.trevorblades.com/');
const sdk = getSdk(client);
const { continents } = await sdk.continents(); // This is fully typed,based on the query
console.log(`GraphQL data:`,continents);
}
我在想:
import {getSdk} from './sdk'
const client = new GraphQLClient('https://countries.trevorblades.com/');
const graphqlBaseQuery = (someGeneratedQueryOrMutation,client) => {
const something = someGeneratedQueryOrMutation(client);
const { continents } = await something.continents();
return { data: continents };
};
代码并没有真正的意义,但我希望你明白我的意思。谢谢:)
解决方法
编辑:现在在 https://www.graphql-code-generator.com/docs/plugins/typescript-rtk-query
上有一个 Grahql Codegen 插件可用其实我几天前就开始写代码生成器的插件了。 您可以在此处查看生成的结果: https://github.com/phryneas/graphql-code-generator/blob/5f9a2eefd81538782b791e0cc5df633935164a89/dev-test/githunt/types.rtk-query.ts#L406-L427
这需要您使用您选择的 graphql 库 like this 创建带有 baseQuery 的 API。
A configuration would look like this
./dev-test/githunt/types.rtk-query.ts:
schema: ./dev-test/githunt/schema.json
documents: ./dev-test/githunt/**/*.graphql
plugins:
- typescript
- typescript-operations
- typescript-rtk-query
config:
importBaseApiFrom: '../../packages/plugins/typescript/rtk-query/tests/baseApi'
exportHooks: true
而且我认为出于捆绑拆分的目的,它也适用于 near-operation-file
预设。
所有这些还没有到上游 - 我会在本周末尝试准备好,但不知道实际需要多长时间才能完成。
您可以检查存储库,进行本地构建并使用 yalc
之类的东西安装它。
对于没有代码生成的更基本的方法,您可以查看 this example 或更高级的设置(但也没有完整的代码生成,与现有工具更加集成)您可以查看 {{3} }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。