Reputation: 111
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 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!
Upvotes: 5
Views: 4463
Reputation: 1713
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!;
};
};
Upvotes: 7