0.0.4 • Published 1 year ago

@onekstar/graphql v0.0.4

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

@onekstar/graphql

install

yarn add @onekstar/graphql @tanstack/react-query

最佳实践(推荐)

  • 将 graphql schema 文件放在src/graphql/**文件夹中,文件名以.gql结尾

  • 创建tools/codegen.ts

import { codegen, ICodegenParams } from "@onekstar/graphql";
import path from "path";

codegen({
  endpoint: "http://localhost:8000/graphql",
  inputDir: path.resolve(__dirname, "../src/graphql"),
  outputDir: path.resolve(__dirname, "../src/graphql"),
  headers: {
    "content-type": "application/json",
  },
});
  • 在 package.json 添加脚本
"scripts": {
    "codegen": "ts-node codegen.ts"
},
  • 执行yarn codegen,将自动生成请求的调用方法
  • 使用 QueryClientProvider 包裹根组件 App
// src/index.tsx

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient();

const App = () => {
  return (
    <QueryClientProvider client={queryClient}>
      <Router />
    </QueryClientProvider>
  );
};

ReactDOM.render(<App />, root);
  • 在项目中调用请求文件中的hooks请求函数即可
// src/pages/Home/index.tsx

import { useGetUserInfoQuery } from "../api";

const Home = () => {
  const { data, isLoading } = useGetUserInfoQuery();

  return <div>{isLoading ? "loading" : data?.name}</div>;
};

export default Home;

自定义编译

codegen 函数的参数如下:

export interface ICodegenParams {
  endpoint: string;
  inputDir: string;
  outputDir: string;
  headers?: {
    [key: string]: any;
  };
}