尝试使用【Next.js】ApolloClient×GraphQLCodegen
首先
因为ApolloClient×GraphqlCodegen的组合非常方便易用,让我深感震撼,所以我将简要总结一下使用方法。
这次我想简要介绍从文件生成到调用API的流程,以用户注册和获取为例。
如果有任何错误,请指正,我将不胜感激。
我这次使用的库
@apollo/client
@graphql-codegen/cli
@graphql-codegen/typescript
@graphql-codegen/typescript-operations
@graphql-codegen/typescript-react-apollo
@graphql-codegen/client-preset
@graphql-codegen/introspection
代码生成.yml
定义生成文件的类型和选项。
通过这个配置,类型定义和Hooks将会自动生成。
overwrite: true
schema: "schema.graphql"
documents: "src/**/*.gql"
generates:
src/generated/graphql.ts:
plugins:
- "typescript"
- "typescript-operations"
- "typescript-react-apollo"
config:
withHooks: true
withComponent: false
withHOC: false
覆盖现有文件吗?
模式文件的路径。
文件(查询、变异等)的路径。
生成的文件的存放位置
插件:
需要進行各種插件的獨立安裝。
配置:
带有Hooks:
启用为Apollo Client生成自定义Hook
withComponent:withHOC:false
禁用生成React组件和高阶组件。
package.json文件
定义自动生成命令
scripts{
"codegen": "graphql-codegen --config codegen.yml"
}
schema.gql模式文件。
定义所使用的数据类型、API的查询和变更。
scalar Upload
type User {
userId: ID!
email: String!
name: String!
}
type Query {
user(userId: ID!): User
}
type Mutation {
createUser(name: String!): User
}
文件
GraphQL的文档定义了应用程序发送到实际GraphQL服务器的操作。以下示例中定义了获取用户和创建新用户的操作。
//User.gql
query GetUser($userId: ID!) {
user(userId: $userId) {
userId
email
name
}
}
mutation CreateUser($name: String!) {
createUser(name: $name) {
userId
email
name
}
}
生成指令
当执行此命令时,将根据codegen.yml中定义的配置自动生成文件。
npx graphql-codegen
阿波罗的准备 de
创建HTTP链接和认证链接,以及Apollo Client实例。
import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
const httpLink = createHttpLink({
uri: "http://hogehoge"
});
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem("token");
return {
headers: {
...headers,
authorization: token
},
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
import type { AppProps } from "next/app";
import { ApolloProvider } from "@apollo/client";
import client from "@/lib/apollo/client";
export default function App({ Component, pageProps }: AppProps) {
return (
<ApolloProvider client={client}>
<AuthProvider>
<Component {...pageProps} />
</AuthProvider>
</ApolloProvider>
);
}
我试试询问
使用ApolloClient的useQuery hook从服务器获取数据。
import { useQuery } from "@apollo/client";
import {
GetUserDocument,
GetUserQuery,
GetUserQueryVariables,
} from "@/generated/graphql";
export const useGetUser = (userId: string) => {
const { data, loading, error } = useQuery<
GetUserQuery,
GetUserQueryVariables
>(GetUserDocument, {
variables: { userId: userId },
});
return { data, loading, error };
};
export default function Home() {
const { data, loading, error } = useGetUser(userId!);
if (loading) return <div>loading...</div>;
if (error) return <div>error</div>;
return (
<div>{data.name}</div>
);
}
我试着敲击变异物。
使用ApolloClient的useMutation钩子函数,向服务器发送更改数据的请求。
import { useMutation } from "@apollo/client";
import {
CreateUserMutation,
CreateUserMutationVariables,
CreateUserDocument,
} from "@/generated/graphql";
export const useCreateUser = () => {
const [createUser, { data, loading, error }] = useMutation<
CreateUserMutation,
CreateUserMutationVariables
>(CreateUserDocument);
return { createUser, data, loading, error };
};
export const CreateUser = () => {
const { createUser, data } = useCreateUser();
const handleCreate = async () => {
try {
await createUser({
variables: { name: userName }
});
console.log("ユーザー登録完了");
}
return data
} catch (err) {
console.log(err);
}
};
以上引述资料