I am using graphql-codegen
yarn package to generate React hooks
graphql-codegen --config codegen.yml
I want to decorate every GraphQL endpoint call with an operation name, so I could see the operation name in the DevTools console:
I have tried to find a Code Generator plugin for this purpose but with no luck. How can I achieve my desired goal?
config codegen.yml:
schema: 'https://localhost:5001/api/graphql/'
overwrite: true
documents: './src/**/*.graphql'
generates:
./src/graphql/schema.graphql:
plugins:
- schema-ast
./src/graphql/graphqlTypes.ts:
- typescript
./src/graphql/:
preset: near-operation-file
presetConfig:
extension: .ts
folder: ../hooks
baseTypesPath: graphqlTypes.ts
plugins:
- typescript-operations
- typescript-rtk-query:
importBaseApiFrom: 'graphql/baseApi'
exportHooks: true
My baseApi.ts
looks like this:
import { createApi, retry } from '@reduxjs/toolkit/query/react';
import { graphqlRequestBaseQuery } from '@rtk-query/graphql-request-base-query';
import { Cookies } from 'react-cookie';
import { GraphQLClient } from 'graphql-request';
const client = new GraphQLClient(
`${process.env.REACT_APP_API_URL}/api/graphql`
);
const cookies = new Cookies();
const token = cookies.get('.AspNetCore.Application.Id');
client.setHeader('authorization', `Bearer ${token}`);
client.setHeader('Content-Type', 'application/json');
client.setHeader('X-Requested-With', 'XMLHttpRequest');
export default client;
const staggeredBaseQuery = retry(graphqlRequestBaseQuery({ client }), {
maxRetries: 2,
});
export const api = createApi({
baseQuery: staggeredBaseQuery,
endpoints: () => ({}),
keepUnusedDataFor: 5,
refetchOnMountOrArgChange: false,
});
My generated hook looks like this:
import * as Types from '../graphqlTypes';
import { api } from 'graphql/baseApi';
export type SetPreferenceMutationVariables = Types.Exact<{
name: Types.Scalars['String'];
value: Types.Scalars['String'];
}>;
export type SetPreferenceMutation = {
__typename?: 'Mutation';
setPreference?: boolean | null | undefined;
};
export const SetPreferenceDocument = `
mutation setPreference($name: String!, $value: String!) {
setPreference(name: $name, value: $value)
}
`;
const injectedRtkApi = api.injectEndpoints({
endpoints: (build) => ({
setPreference: build.mutation<
SetPreferenceMutation,
SetPreferenceMutationVariables
>({
query: (variables) => ({ document: SetPreferenceDocument, variables }),
}),
}),
});
export { injectedRtkApi as api };
export const { useSetPreferenceMutation } = injectedRtkApi;
I found this piece of code: graphql-code-generator/packages/plugins/typescript/rtk-query/src/visitor.ts but I could not find the option to update the URL. Looks like I need to write my own plugin.