From 3ecdd265c29906923c24ab1870a601611a628afc Mon Sep 17 00:00:00 2001 From: Matchu Date: Sat, 12 Sep 2020 22:39:38 -0700 Subject: [PATCH] smarter cache lookups for "do we own/want this?" --- src/app/ItemPage.js | 7 +++--- src/app/apolloClient.js | 47 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/app/ItemPage.js b/src/app/ItemPage.js index 487aa3f..340f9e3 100644 --- a/src/app/ItemPage.js +++ b/src/app/ItemPage.js @@ -198,8 +198,8 @@ function ItemPageOwnWantButtons({ itemId }) { { variables: { itemId }, onCompleted: (data) => { - setCurrentUserOwnsThis(data.item.currentUserOwnsThis); - setCurrentUserWantsThis(data.item.currentUserWantsThis); + setCurrentUserOwnsThis(data?.item?.currentUserOwnsThis || false); + setCurrentUserWantsThis(data?.item?.currentUserWantsThis || false); }, } ); @@ -208,6 +208,7 @@ function ItemPageOwnWantButtons({ itemId }) { return {error.message}; } + // TODO: Focus state! return ( @@ -215,7 +216,7 @@ function ItemPageOwnWantButtons({ itemId }) { { setCurrentUserOwnsThis(e.target.checked); toast({ diff --git a/src/app/apolloClient.js b/src/app/apolloClient.js index 926ad1c..0b9e37d 100644 --- a/src/app/apolloClient.js +++ b/src/app/apolloClient.js @@ -78,6 +78,53 @@ const typePolicies = { return undefined; } }, + + currentUserOwnsThis: (cachedValue, { readField }) => { + if (cachedValue != null) { + return cachedValue; + } + + // Do we know what items this user owns? If so, scan for this item. + const currentUserRef = readField("currentUser", { + __ref: "ROOT_QUERY", + }); + if (!currentUserRef) { + return undefined; + } + const thisItemId = readField("id"); + const itemsTheyOwn = readField("itemsTheyOwn", currentUserRef); + if (!itemsTheyOwn) { + return undefined; + } + + const theyOwnThisItem = itemsTheyOwn.some( + (itemRef) => readField("id", itemRef) === thisItemId + ); + return theyOwnThisItem; + }, + currentUserWantsThis: (cachedValue, { readField }) => { + if (cachedValue != null) { + return cachedValue; + } + + // Do we know what items this user owns? If so, scan for this item. + const currentUserRef = readField("currentUser", { + __ref: "ROOT_QUERY", + }); + if (!currentUserRef) { + return undefined; + } + const thisItemId = readField("id"); + const itemsTheyWant = readField("itemsTheyWant", currentUserRef); + if (!itemsTheyWant) { + return undefined; + } + + const theyWantThisItem = itemsTheyWant.some( + (itemRef) => readField("id", itemRef) === thisItemId + ); + return theyWantThisItem; + }, }, }, };