【问题标题】:Use RTK Query with Graphql使用带有 Graphql 的 RTK 查询
【发布时间】:2021-08-19 22:05:12
【问题描述】:

到目前为止,我知道我需要建立自己的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-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 };
    };

代码并没有真正的意义,但我希望你能明白我的意思。谢谢:)

【问题讨论】:

    标签: graphql-codegen rtk-query


    【解决方案1】:

    编辑:现在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。

    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 预设一起使用。

    所有这些还不是上游的——我会在这个周末试着把它准备好,但不知道要花多少时间才能真正把它放进去。

    您可以检查 repo,进行本地构建并使用 yalc 之类的东西安装它。

    对于没有代码生成的更基本的方法,您可以查看this example,或者对于更高级的设置(但也没有完整的代码生成,与现有工具更集成),您可以查看this PR

    【讨论】:

    猜你喜欢
    • 2022-08-03
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    • 2021-12-18
    • 2023-01-31
    • 2017-02-21
    • 2020-09-28
    • 2019-10-20
    相关资源
    最近更新 更多