From eab1b99052ed88d6926b7fea4dc9f2959a09efce Mon Sep 17 00:00:00 2001 From: Matchu Date: Tue, 1 Sep 2020 18:02:59 -0700 Subject: [PATCH] use cache restore instead of field defs for Zone This is just an implementation thing, but I realized we can just insert the Zone data into the initial Apollo cache, instead of doing weird field definitions I _do_ still want the @client tags in the queries though, to tell them not to make server requests at all --- src/app/apolloClient.js | 33 +++++++-------------------------- 1 file changed, 7 insertions(+), 26 deletions(-) diff --git a/src/app/apolloClient.js b/src/app/apolloClient.js index 1380b00..6ffa7fc 100644 --- a/src/app/apolloClient.js +++ b/src/app/apolloClient.js @@ -2,8 +2,7 @@ import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client"; import { createPersistedQueryLink } from "apollo-link-persisted-queries"; import gql from "graphql-tag"; -const cachedZones = require("./cached-data/zones.json"); -const cachedZonesById = new Map(cachedZones.map((z) => [z.id, z])); +import cachedZones from "./cached-data/zones.json"; // Teach Apollo to load certain fields from the cache, to avoid extra network // requests. This happens a lot - e.g. reusing data from item search on the @@ -93,29 +92,6 @@ const typePolicies = { }, }, }, - - Zone: { - fields: { - depth: (depth, { readField }) => { - const id = readField("id"); - return depth || cachedZonesById.get(id)?.depth || 0; - }, - - label: (label, { readField }) => { - const id = readField("id"); - return label || cachedZonesById.get(id)?.label || `Zone #${id}`; - }, - - isCommonlyUsedByItems: (isCommonlyUsedByItems, { readField }) => { - const id = readField("id"); - return ( - isCommonlyUsedByItems || - cachedZonesById.get(id)?.isCommonlyUsedByItems || - false - ); - }, - }, - }, }; // The PersistedQueryLink in front of the HttpLink helps us send cacheable GET @@ -125,13 +101,18 @@ const persistedQueryLink = createPersistedQueryLink({ }); const httpLink = createHttpLink({ uri: "/api/graphql" }); +const initialCache = {}; +for (const zone of cachedZones) { + initialCache[`Zone:${zone.id}`] = { __typename: "Zone", ...zone }; +} + /** * apolloClient is the global Apollo Client instance we use for GraphQL * queries. This is how we communicate with the server! */ const client = new ApolloClient({ link: persistedQueryLink.concat(httpLink), - cache: new InMemoryCache({ typePolicies }), + cache: new InMemoryCache({ typePolicies }).restore(initialCache), connectToDevTools: true, });