React Query + Codegen - custom fetcher
Asked Answered
L

1

5

I use a codegen + react query + my own fetcher to deal with API calls. https://www.graphql-code-generator.com/plugins/typescript-react-query#using-fetch-with-codegen-configuration

My requirements:

  • I need to have a custom fetcher - to resolve custom backend errors (I need to extract some information from a response)
  • I need to have an option to pass additional headers for each query (so my generated hook need to be able to take some extra params and use them in an API call)

I think option: fetcher: 'fetch' works with my second requirement (I am able to put extra headers/endpoints for each hook), but I can't throw graphql errors using my own format (there is a default throw that comes from native fetch method).

Is there any option to create a solution (maybe combining a proper config + custom fetcher) to meet both requirements? Thanks!

Lilybelle answered 28/1, 2022 at 9:38 Comment(1)
Hey were you able to figure out? Having same issueForb
S
7

GraphQL Codegen supports custom fetcher functions by its ./my-file#myFetcher notation.

For example, I use a custom fetcher for AWS Amplify to include authentication headers (API key, User Pool, etc.):

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!;
  };
};

Spillway answered 7/4, 2022 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.