从传统的gql前端字符串模版中解脱出来,搭配ts的类型推导,可以更加简便的实现前端请求的处理。
从GraphQL模式生成代码
使用简单的CLI从GraphQL模式和操作生成代码
立即生成代码
使用单个函数调用从GraphQL模式和GraphQL操作生成代码,而不考虑环境或代码格式。
轻松自定义
配合前端各种框架,轻松实现自定义代码脚本,各种钩子处理。比如代码格式化,切分等。
安装
# @graphql-codegen/cli
$ yarn add graphql @apollo/client
$ yarn add @graphql-codegen/cli -D
$ yarn add @graphql-codegen/import-types-preset @graphql-codegen/introspection -D
$ yarn add @graphql-codegen/typescript @graphql-codegen/typescript-document-nodes -D
$ yarn add @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo -D
$ yarn add @graphql-codegen/typescript-react-query -D
package.json
script:
"generator": "graphql-codegen --config operation.yml"
配置文件 operation.yml
hooks:
# 格式化
afterAllFileWrite:
- prettier --write
overwrite: true
schema: 'http://127.0.0.1:8061/graphql'
documents: 'graphql/**/*.gql'
generates:
# 基础类型
src/generator/foundation.ts:
plugins:
- 'typescript'
- 'typescript-operations'
# 操作
src/generator/foundation.operation.ts:
preset: import-types
presetConfig:
typesPath: ./foundation
importTypesNamespace: SchemaTypes
plugins:
- 'typescript-react-apollo'
config:
# defaultBaseOptions: {
# fetchPolicy: 'cache-and-network'
# }
# src/generator/auth-center.operation.ts:
# plugins:
# - 'typescript-react-apollo'
config:
immutableTypes: true
使用
- main.tsx
import './index.css';
import { ProConfigProvider } from '@ant-design/pro-components';
import {
ApolloClient,
ApolloProvider,
createHttpLink,
InMemoryCache,
} from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { RouterProvider } from 'react-router-dom';
import store from './redux/store.ts';
import { router } from './router/index.tsx';
const httpLink = createHttpLink({
uri: import.meta.env.VITE_BASE_GQL_URL,
});
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
// const token = localStorage.getItem('token');
const jwtToken = store.getState()?.login?.appUser?.accessToken;
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: jwtToken ? `Bearer ${jwtToken}` : '',
},
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'all',
},
query: {
fetchPolicy: 'network-only',
errorPolicy: 'all',
},
mutate: {
errorPolicy: 'all',
},
},
});
createRoot(document.getElementById('root')!).render(
<ApolloProvider client={client}>
<ProConfigProvider dark>
<Provider store={store}>
<RouterProvider router={router} />
</Provider>
</ProConfigProvider>
</ApolloProvider>
);