Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

What is the best way to handle the react GQL configurations with all query and mutation policies and for file upload?

Need to know the best practice to maintain the react GQL configurations settings where we set all query, mutation, or other policies, and the better way to handle file upload setting?

question from:https://stackoverflow.com/questions/65937155/what-is-the-best-way-to-handle-the-react-gql-configurations-with-all-query-and-m

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are many approaches with different use cases. The following code might be helpful in your case.

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...