【发布时间】:2021-05-02 08:24:58
【问题描述】:
需要了解维护我们设置所有查询、突变或其他策略的 React GQL 配置设置的最佳实践,以及处理文件上传设置的更好方法吗?
【问题讨论】:
需要了解维护我们设置所有查询、突变或其他策略的 React GQL 配置设置的最佳实践,以及处理文件上传设置的更好方法吗?
【问题讨论】:
有许多不同用例的方法。以下代码可能对您有所帮助。
import {
ApolloClient,
ApolloLink,
DefaultOptions,
InMemoryCache,
} from "@apollo/client";
import { onError } from "@apollo/client/link/error";
import { createUploadLink } from "apollo-upload-client";
const authMiddleware = new ApolloLink((operation: any, forward: any) => {
const token = localStorage.getItem("token") || null;
operation.setContext({
headers: {
authorization: `Bearer ${token}`,
},
});
return forward(operation);
});
const defaultOptions: DefaultOptions = {
watchQuery: {
fetchPolicy: "cache-and-network",
errorPolicy: "ignore",
},
query: {
fetchPolicy: "network-only",
errorPolicy: "all",
},
mutate: {
errorPolicy: "all",
},
};
const errorLink = onError(
({ graphQLErrors, networkError, operation, forward }: any) => {
// You can modify do something with the errors
}
);
const client = new ApolloClient({
cache: new InMemoryCache(),
connectToDevTools: true,
link: ApolloLink.from([
errorLink,
authMiddleware,
createUploadLink({
uri: process.env.REACT_APP_GRAPHQL_URI || "http://localhost:3001/graphql",
}),
]),
defaultOptions: defaultOptions,
});
export default client;
【讨论】: