使用RTK Query和Graphql。

4
到目前为止,我了解到我需要构建自己的baseQuery。我可以像这个例子中写graphql查询和变异一样:https://rtk-query-docs.netlify.app/examples/react-with-graphql,如果我向query.builder添加类型如builder.query<Device, void>,我是否会获得完整的查询和变异类型安全性,或者我必须使用类似于https://www.graphql-code-generator.com/docs/plugins/typescript-graphql-request#simple-request-middleware的东西。在后一种情况下,如果我使用生成的钩子(graphql-request库),我的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 };
    };

代码不是很有意义,但我希望你能理解我的意思。谢谢 :)

1个回答

1

编辑:现在有一个Grahql Codegen插件可用于https://www.graphql-code-generator.com/docs/plugins/typescript-rtk-query


实际上,我几天前开始编写代码生成器的插件。 您可以在此处查看生成的结果: https://github.com/phryneas/graphql-code-generator/blob/5f9a2eefd81538782b791e0cc5df633935164a89/dev-test/githunt/types.rtk-query.ts#L406-L427

这将要求您使用自己选择的graphql库创建一个带有baseQuery的api (类似于此)

配置将如下所示

  ./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,或者对于稍微高级一点的设置(也没有完全的代码生成,更加集成了现有的工具)可以查看this PR


1
你在 Github 上帮了我 :D - Nenad
仅作更新:graphql codegen插件现已可用。https://www.graphql-code-generator.com/docs/plugins/typescript-rtk-query - phry
链接失效了 :o( 伤心 - Jeremy
1
@Jeremy https://www.the-guild.dev/graphql/codegen/plugins/typescript/typescript-rtk-query - phry
GraphQL无需代码生成工具,可以在此处找到:https://github.com/reduxjs/redux-toolkit/blob/master/examples/query/react/graphql/src/app/services/posts.ts - Bruce Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接