GraphQl代码生成器:用查询字符串装饰URL
我正在使用 graphql-codegen
纱软件包来生成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. 我该如何实现所需的目标?
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/typecript/rtk-query/src/visitor.ts ,但我找不到更新URL的选项。 看来我需要编写自己的插件。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
希望以下信息会有所帮助。
如果您想能够使用多个端点,则可以创建您的链接,例如:
必须向每个查询提供额外的代码:
源:官方文档。
Hope below info will help.
If you want to be able to use multiple endpoints, you can create your link like:
Extra code has to be provided to each query:
Source: official docs.