@apollo/client#InMemoryCache TypeScript Examples

The following examples show how to use @apollo/client#InMemoryCache. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** @internal */
    private async createClient() {
        let doneInit: (() => void) | undefined;
        this.initializePromise = new Promise<void>(done => doneInit = done);

        if (isServer()) {
            // If backend, try to find service secret key to make 
            // authorized requests to the API server.
            this.serviceSecret = await getServiceSecret();
        }

        const cache = new InMemoryCache();
        const link = createHttpLink({
            uri: this.getBaseUrl(),
            credentials: 'include',
            fetch: this.fetch,
            headers: this.serviceSecret && { 'Authorization': `Service ${this.serviceSecret}` },
        });

        this.apolloClient = new ApolloClient({
            cache: cache,
            link: link,
            name: 'cromwell-core-client',
            queryDeduplication: false,
            defaultOptions: {
                query: {
                    fetchPolicy: 'network-only',
                },
                watchQuery: {
                    fetchPolicy: 'cache-and-network',
                },
            },
        });

        doneInit?.();
        this.initializePromise = undefined;
    }
Example #2
Source File: index.tsx    From Insomniac-NextJS-boilerplate with MIT License 6 votes vote down vote up
function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: new HttpLink({
      uri: process.env.NEXT_PUBLIC_API_URL, // Server URL (must be absolute)
    }),
    cache: new InMemoryCache(),
  });
}
Example #3
Source File: initApollo.tsx    From nft-marketplace with European Union Public License 1.2 6 votes vote down vote up
function create(initialState) {
  const httpLink = new HttpLink({
    uri: GRAPHQL_ENDPOINT,
    credentials: 'same-origin',
  });

  return new ApolloClient({
    connectToDevTools: process.browser,
    ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
    link: httpLink,
    cache: new InMemoryCache({ possibleTypes }).restore(initialState || {}),
  });
}
Example #4
Source File: withApollo.tsx    From NextJS-NestJS-GraphQL-Starter with MIT License 6 votes vote down vote up
withApollo = nextWithApollo(
  ({ initialState, headers, ...rest }) => {
    const httpLink = new HttpLink({
      uri: IS_SERVER ? SERVER_API_ENDPOINT : BROWSER_API_ENDPOINT,
      headers: {
        ...headers
      },
      credentials: 'include'
    });

    return new ApolloClient({
      ssrMode: IS_SERVER,
      link: httpLink,
      cache: new InMemoryCache().restore(initialState || {}),
      // A hack to get ctx oin the page's props on the initial render
      // @ts-ignore
      defaultOptions: { ...rest }
    });
  },
  {
    render: ({ Page, props }) => {
      return (
        <ApolloProvider client={props.apollo}>
          <Page {...props} {...props.apollo.defaultOptions.ctx} />
        </ApolloProvider>
      );
    }
  }
)
Example #5
Source File: cache.ts    From nextjs-hasura-fullstack with MIT License 6 votes vote down vote up
cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        feeds: concatPagination(),
        // boards: {
        //   merge(existing = [], incoming: any[]) {
        //     return [...existing, ...incoming]
        //   },
        // },
      },
    },
  },
})
Example #6
Source File: App.tsx    From graphql-schema-registry with MIT License 6 votes vote down vote up
App = ({ api }: AppProps) => {
	const config = createConfig(api);

	const client = new ApolloClient({
		cache: new InMemoryCache(),
		link: new HttpLink({
			uri: config.grapqhlEndpoint,
			credentials: 'include',
		}),
	});

	return (
		<GlobalConfigContext.Provider value={config}>
			<ApolloProvider client={client}>
				<Main />
			</ApolloProvider>
		</GlobalConfigContext.Provider>
	);
}
Example #7
Source File: client.ts    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
getClient = (): ApolloClient<NormalizedCacheObject> => {
  if (!client) {
    const config = getConfig() as NextConfigType

    if (!config) return client

    const { publicRuntimeConfig, serverRuntimeConfig } = config

    client = new ApolloClient<NormalizedCacheObject>({
      cache: new InMemoryCache(),
      link: from([
        setContext((request, context) => {
          const headers: { [key: string]: string } = {}

          if (process.browser) {
            const access = localStorage.getItem('access')

            if (access) {
              headers.authorization = `Bearer ${access}`
            }
          }

          return {
            headers,
          }
        }),
        new HttpLink({
          uri: serverRuntimeConfig.endpoint || publicRuntimeConfig.endpoint,
        }),
      ]),
    })
  }

  return client
}
Example #8
Source File: withData.tsx    From keycapsets.com with GNU General Public License v3.0 6 votes vote down vote up
function createApolloClient() {
    const isBrowser: boolean = typeof window === 'undefined';
    return new ApolloClient({
        ssrMode: isBrowser,
        link: authLink.concat(
            createUploadLink({
                uri: apiUrl,
            })
        ),
        cache: new InMemoryCache(),
    });
}
Example #9
Source File: apolloClient.ts    From next-page-tester with MIT License 6 votes vote down vote up
function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: new HttpLink({
      uri: 'https://nextjs-graphql-with-prisma-simple.vercel.app/api', // Server URL (must be absolute)
      credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
      fetch,
    }),
    cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            allPosts: concatPagination(),
          },
        },
      },
    }),
  });
}
Example #10
Source File: index.ts    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
caches: Record<AllGqlEndpoints, InMemoryCache> = Object.freeze({
  blocks: new InMemoryCache(),
  feeders: new InMemoryCache(),
  merkleDrop: new InMemoryCache(),
  protocol: new InMemoryCache(),
  stakingRewards: new InMemoryCache(),
  snapshot: new InMemoryCache(),
  staking,
  questbook: new InMemoryCache(),
  emissions: new InMemoryCache(),
})
Example #11
Source File: nextApollo.ts    From liferay-grow with MIT License 6 votes vote down vote up
function createApolloClient() {
  const Authorization = getToken();

  return new ApolloClient({
    cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            allPosts: concatPagination(),
          },
          keyFields: ['id'],
        },
      },
    }),
    link: new HttpLink({
      credentials: 'same-origin',
      headers: {
        Authorization,
      },
      uri: `${baseURL}/graphql`,
    }),
    ssrMode: typeof window === 'undefined',
  });
}
Example #12
Source File: index.ts    From fullstack-starterkit with MIT License 6 votes vote down vote up
function configureApolloClient(config: Config): ApolloClient<NormalizedCacheObject> {
  const httpLink = new HttpLink({ uri: config.endpoints.https });

  const wsLink = new WebSocketLink({
    uri: config.endpoints.wss,
    options: { reconnect: true }
  });

  const link = split(
    ({ query }) => {
      const definition = getMainDefinition(query);
      return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
    },
    wsLink,
    httpLink
  );

  const client = new ApolloClient({
    link: ApolloLink.from([
      onError(({ graphQLErrors, networkError }) => {
        if (graphQLErrors) {
          graphQLErrors.forEach(({ message, locations, path }) =>
            console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
          );
        }

        if (networkError) {
          console.log(`[Network error]: ${networkError}`);
        }
      }),
      link
    ]),
    cache: new InMemoryCache()
  });

  return client;
}
Example #13
Source File: apolloclient.ts    From glific-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        contactHistory: {
          keyArgs: false,

          merge(existing, incoming, { args }: any) {
            if (args.opts.offset === 0) {
              return incoming;
            }
            return [...existing, ...incoming];
          },
        },
      },
    },
  },
})
Example #14
Source File: with-graphql.tsx    From nextjs-strapi-boilerplate with MIT License 6 votes vote down vote up
WithGraphQL = ({
  session,
  children,
}: {
  session: session;
  children: ReactNode;
}) => {
  const token = session?.jwt?.toString();

  const client = new ApolloClient({
    uri:
      `${process.env.NEXT_PUBLIC_API_URL}/graphql` ||
      "http://localhost:1337/graphql",
    credentials: "same-origin",
    cache: new InMemoryCache(),
    headers: {
      authorization: `Bearer ${token}`,
    },
  });

  return <ApolloProvider client={client}>{children}</ApolloProvider>;
}
Example #15
Source File: withApollo.ts    From lireddit with MIT License 6 votes vote down vote up
createClient = (ctx: NextPageContext) =>
  new ApolloClient({
    uri: process.env.NEXT_PUBLIC_API_URL as string,
    credentials: "include",
    headers: {
      cookie:
        (typeof window === "undefined"
          ? ctx?.req?.headers.cookie
          : undefined) || "",
    },
    cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            posts: {
              keyArgs: [],
              merge(
                existing: PaginatedPosts | undefined,
                incoming: PaginatedPosts
              ): PaginatedPosts {
                return {
                  ...incoming,
                  posts: [...(existing?.posts || []), ...incoming.posts],
                };
              },
            },
          },
        },
      },
    }),
  })
Example #16
Source File: apollo.ts    From storefront with MIT License 6 votes vote down vote up
export default function createClient({
  initialState = {},
}: { initialState?: NormalizedCacheObject } = {}) {
  if (apolloClient == null) {
    apolloClient = new ApolloClient({
      // eslint-disable-next-line unicorn/prefer-spread
      link: errorLink.concat(
        // eslint-disable-next-line unicorn/prefer-spread
        authLink.concat(
          // eslint-disable-next-line unicorn/prefer-spread
          afterware.concat(
            createHttpLink({
              uri: process.env.GRAPHQL_URL,
              credentials: 'include',
            }),
          ),
        ),
      ),
      cache: new InMemoryCache({ possibleTypes: introspectionResult.possibleTypes }).restore(
        initialState,
      ),
    });
  }
  return apolloClient;
}
Example #17
Source File: client.ts    From Frontend with MIT License 6 votes vote down vote up
createClient = () => {
  const uri = process.env.GATSBY_GRAPHQL_ENDPOINT;

  const httpLink = createHttpLink({
    uri,
    fetch
  });

  const authToken = hasWindow ? localStorage.getItem('token') : '';

  const authLink = new ApolloLink((operation, forward) => {
    operation.setContext({
      headers: {
        authorization: authToken ? `Bearer ${authToken}` : ''
      }
    });

    return forward(operation);
  });

  const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache({
      dataIdFromObject: (object) => {
        // eslint-disable-next-line no-underscore-dangle
        switch (object.__typename) {
          case 'Person':
            return object.uid;
          default:
            return defaultDataIdFromObject(object); // fall back to default handling
        }
      }
    })
  });

  return client;
}
Example #18
Source File: Security.test.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
async function createSecurity(permsMockConfig?: PermsMockConfig): Promise<Security> {
  const mockApolloClient = new ApolloClient<{}>({
    link: new MockLink([{
      request: {
        query: PERMISSIONS_QUERY,
      },
      result: {
        data: {
          permissions: createPerms(permsMockConfig),
        },
      },
    }]),
    cache: new InMemoryCache({})
  });
  return new Security(mockApolloClient);
}
Example #19
Source File: apolloClient.ts    From react-native-network-logger with MIT License 5 votes vote down vote up
client = new ApolloClient({
  uri: 'https://48p1r2roz4.sse.codesandbox.io',
  cache: new InMemoryCache(),
})
Example #20
Source File: apollo.ts    From HoldemSolver with MIT License 5 votes vote down vote up
client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
})
Example #21
Source File: index.tsx    From ledokku with MIT License 5 votes vote down vote up
apolloClient = new ApolloClient({
  link: from([authLink, errorLink, splitLink]),
  cache: new InMemoryCache(),
})
Example #22
Source File: client.ts    From lexicon with MIT License 5 votes vote down vote up
cache = new InMemoryCache({
  typePolicies: {
    TopicDetailOutput: {
      fields: {
        title: replaceDataPagination(),
        views: replaceDataPagination(),
        likeCount: replaceDataPagination(),
        postsCount: replaceDataPagination(),
        liked: replaceDataPagination(),
        categoryId: replaceDataPagination(),
        tags: replaceDataPagination(),
        createdAt: replaceDataPagination(),
        details: replaceDataPagination(),
      },
    },
    PostStream: {
      fields: {
        posts: prependAppendPagination(),
        stream: replaceDataPagination(),
      },
    },
    Post: {
      fields: {
        actionsSummary: replaceDataPagination(),
        hidden: replaceDataPagination(),
        raw: replaceDataPagination(),
      },
    },
    PostRaw: {
      fields: {
        raw: replaceDataPagination(),
      },
    },
    Query: {
      fields: {
        notification: appendPagination(false, 'NOTIFICATIONS'),
        privateMessage: appendPagination(false, 'MESSAGE_DETAIL'),
        search: appendPagination(false, 'SEARCH'),
        topicDetail: replaceDataPagination(['topicId']),
        topics: appendPagination(['sort', 'categoryId'], 'HOME'),
        userActivity: userActivityPagination(['username']),
      },
    },
  },
})
Example #23
Source File: Shell.tsx    From dh-web with GNU General Public License v3.0 5 votes vote down vote up
Shell: FC<ShellProperties> = ({ children }: ShellProperties) => {

    // get the authentication token from local storage if it exists
    const authToken = useSelector(getAuthenticationToken);

    const bearerString = authToken && `Bearer ${authToken}`;
    // cross platform web socketing triage (tldr use node lib on server and web lib on browser)
    const webSocketImplementation = process.browser ? WebSocket : ws;

    const wsLink = new WebSocketLink({
        uri: "wss://api.dogehouse.online/graphql",
        options: {
            reconnect: true,
            lazy: true,
            timeout: 3000,
            connectionParams: {
                authorization: bearerString
            }
        },
        webSocketImpl: webSocketImplementation
    });

    const httpLink = createHttpLink({
        uri: "https://api.dogehouse.online/graphql",
    });

    const authLink = setContext((_, { headers }) => {
        // return the headers to the context so httpLink can read them
        return {
            headers: {
                ...headers,
                authorization: bearerString,
            }
        };
    });

    const splitLink = split(
        ({ query }) => {
            const definition = getMainDefinition(query);
            return (
                definition.kind === "OperationDefinition" &&
                definition.operation === "subscription"
            );
        },
        wsLink,
        (authLink.concat(httpLink)),
    );

    const client = new ApolloClient({
        link: from([errorLink, splitLink]),
        cache: new InMemoryCache(),
    });

    return (
        <ThemeProvider theme={DarkTheme}>
            <ApolloProvider client={client}>
                <GlobalStyle />
                <Head>
                    <link rel="preconnect" href="https://fonts.gstatic.com" />
                    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet" />
                </Head>
                <Wrapper>
                    <NoSsr>
                        {
                            children
                        }
                    </NoSsr>
                </Wrapper>
            </ApolloProvider>
        </ThemeProvider>
    );
}
Example #24
Source File: index.tsx    From tinyhouse with MIT License 5 votes vote down vote up
client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
})
Example #25
Source File: ApolloProvider.tsx    From mStable-apps with GNU Lesser General Public License v3.0 5 votes vote down vote up
dummyClient = new ApolloClient<NormalizedCacheObject>({ cache: new InMemoryCache() })
Example #26
Source File: cache.ts    From taskcafe with MIT License 5 votes vote down vote up
cache = new InMemoryCache()
Example #27
Source File: staking.ts    From mStable-apps with GNU Lesser General Public License v3.0 5 votes vote down vote up
staking = new InMemoryCache({
  typePolicies,
})
Example #28
Source File: graphql.ts    From index-ui with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2',
  }),
  cache: new InMemoryCache(),
})
Example #29
Source File: subgraph.ts    From nouns-monorepo with GNU General Public License v3.0 5 votes vote down vote up
clientFactory = (uri: string) =>
  new ApolloClient({
    uri,
    cache: new InMemoryCache(),
  })