chukwuyem

Apollo Client

Dec 12th, 2020
668
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { ApolloClient, InMemoryCache, NormalizedCacheObject, ApolloLink, operationName, from } from "@apollo/client";
  2. import {useMemo} from "react";
  3. import { forwardRef } from "react/cjs/react.production.min";
  4.  
  5.  
  6.  
  7. let apolloClient : ApolloClient<NormalizedCacheObject>;
  8.  
  9.  
  10.  
  11. function createIsomorphicLink(){
  12.     if (typeof window === "undefined"){
  13.         const {SchemaLink} = require("@apollo/client/link/schema");
  14.         const {schema} = require("./schema.ts");
  15.         return new SchemaLink({schema});
  16.     } else {
  17.         const {HttpLink} = require("@apollo/client/link/http");
  18.         return new HttpLink({uri: "/api/graphql"})
  19.     }
  20. }
  21.  
  22. const authMiddleware = new ApolloLink((operation, forward) => {
  23.     operation.setContext(({headers}: {headers? : any})=>{
  24.         return {
  25.             headers: {
  26.                 ...headers,
  27.                 authorization:
  28.                 (global.localStorage && global.localStorage.getItem("token")) ||
  29.                 undefined,
  30.             },
  31.         }
  32.     })
  33.     return forward(operation)
  34. })
  35.  
  36. // console.log(authMiddleware)
  37.  
  38. function createApolloClient(){
  39.     return new ApolloClient({
  40.         ssrMode: typeof window === "undefined",
  41.         link: from([authMiddleware, createIsomorphicLink()]),
  42.         cache: new InMemoryCache()
  43.     })
  44. }
  45.  
  46. export function initilizeApollo(initialState = null){
  47.     const _apolloClient = apolloClient ?? createApolloClient();
  48.     if (initialState){
  49.         _apolloClient.cache.restore(initialState);
  50.     }
  51.     if(typeof window === "undefined") return _apolloClient;
  52.     apolloClient = apolloClient ?? _apolloClient;
  53.     return apolloClient;
  54. }
  55.  
  56. export function useApollo(initialState){
  57.     const store = useMemo(() => initilizeApollo(initialState), [initialState])
  58.     return store;
  59. }
RAW Paste Data