【问题标题】:What is the best way to handle the react GQL configurations with all query and mutation policies and for file upload?使用所有查询和突变策略以及文件上传处理反应 GQL 配置的最佳方法是什么?
【发布时间】:2021-05-02 08:24:58
【问题描述】:

需要了解维护我们设置所有查询、突变或其他策略的 React GQL 配置设置的最佳实践,以及处理文件上传设置的更好方法吗?

【问题讨论】:

    标签: gql react-gql


    【解决方案1】:

    有许多不同用例的方法。以下代码可能对您有所帮助。

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多