【问题标题】:React Query + Codegen - custom fetcherReact Query + Codegen - 自定义提取器
【发布时间】:2022-04-07 21:10:22
【问题描述】:

我使用 codegen + react 查询 + 我自己的 fetcher 来处理 API 调用。 https://www.graphql-code-generator.com/plugins/typescript-react-query#using-fetch-with-codegen-configuration

我的要求:

  • 我需要一个自定义提取器 - 以解决自定义后端错误(我需要从响应中提取一些信息)
  • 我需要有一个选项来为每个查询传递额外的标头(因此我生成的钩子需要能够获取一些额外的参数并在 API 调用中使用它们)

我认为选项:fetcher: 'fetch' 适用于我的第二个要求(我可以为每个钩子放置额外的标头/端点),但我不能使用我自己的格式抛出 graphql 错误(有一个默认抛出来自本机 fetch 方法)。

是否有任何选项可以创建一个解决方案(可能结合适当的配置 + 自定义提取器)来满足这两个要求? 谢谢!

【问题讨论】:

  • 嘿,你能弄清楚吗?有同样的问题

标签: reactjs react-query codegen


【解决方案1】:

GraphQL Codegen 通过其./my-file#myFetcher 表示法支持custom fetcher functions

例如,我使用 AWS Amplify 的自定义提取器来包含身份验证标头(API 密钥、用户池等):

codegen.yml

generates:
  src/graphql/api.ts:
    plugins:
      - typescript
      - typescript-operations
    config:
      fetcher: './fetcher#fetchWithAmplify'

fetcher.ts

import { API, graphqlOperation, GraphQLResult } from '@aws-amplify/api';

export const fetchWithAmplify = <TData, TVariables>(query: string, variables?: TVariables, options?: RequestInit['headers']): (() => Promise<TData>) => {
  return async () => {
    const result = await (API.graphql({
      query,
      variables: variables || {},
      authMode: 'AMAZON_COGNITO_USER_POOLS',
    }) as unknown as Promise<GraphQLResult<TData>>);

    if (result.errors) {
      const message = result.errors ? result.errors[0].message : 'GraphQL fetching error';
      throw new Error(message);
    }

    return result.data!;
  };
};

【讨论】:

    猜你喜欢
    • 2023-01-21
    • 2017-04-22
    • 2012-09-18
    • 2016-08-16
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多