Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { ApolloClient, InMemoryCache, NormalizedCacheObject, ApolloLink, operationName, from } from "@apollo/client";
- import {useMemo} from "react";
- import { forwardRef } from "react/cjs/react.production.min";
- let apolloClient : ApolloClient<NormalizedCacheObject>;
- function createIsomorphicLink(){
- if (typeof window === "undefined"){
- const {SchemaLink} = require("@apollo/client/link/schema");
- const {schema} = require("./schema.ts");
- return new SchemaLink({schema});
- } else {
- const {HttpLink} = require("@apollo/client/link/http");
- return new HttpLink({uri: "/api/graphql"})
- }
- }
- const authMiddleware = new ApolloLink((operation, forward) => {
- operation.setContext(({headers}: {headers? : any})=>{
- return {
- headers: {
- ...headers,
- authorization:
- (global.localStorage && global.localStorage.getItem("token")) ||
- undefined,
- },
- }
- })
- return forward(operation)
- })
- // console.log(authMiddleware)
- function createApolloClient(){
- return new ApolloClient({
- ssrMode: typeof window === "undefined",
- link: from([authMiddleware, createIsomorphicLink()]),
- cache: new InMemoryCache()
- })
- }
- export function initilizeApollo(initialState = null){
- const _apolloClient = apolloClient ?? createApolloClient();
- if (initialState){
- _apolloClient.cache.restore(initialState);
- }
- if(typeof window === "undefined") return _apolloClient;
- apolloClient = apolloClient ?? _apolloClient;
- return apolloClient;
- }
- export function useApollo(initialState){
- const store = useMemo(() => initilizeApollo(initialState), [initialState])
- return store;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement