From 608c951b5b9bde26395d539ed226f4a72f5f151d Mon Sep 17 00:00:00 2001 From: Hugo Morosini Date: Tue, 26 Oct 2021 14:32:09 +0200 Subject: [PATCH] added expiration logic --- src/nft/NftMetadataProvider/index.tsx | 11 ++++++----- src/nft/NftMetadataProvider/logic.ts | 20 ++++++++++++++++++++ src/nft/NftMetadataProvider/types.ts | 1 + 3 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 src/nft/NftMetadataProvider/logic.ts diff --git a/src/nft/NftMetadataProvider/index.tsx b/src/nft/NftMetadataProvider/index.tsx index 1bdbc44197..f5fe70cde7 100644 --- a/src/nft/NftMetadataProvider/index.tsx +++ b/src/nft/NftMetadataProvider/index.tsx @@ -17,6 +17,7 @@ import { NFTMetadataContextType, NFTResource, } from "./types"; +import { isOutdated } from "./logic"; const currency: Currency = findCryptoCurrencyById("ethereum")!; const ethApi: API = apiForCurrency(currency); @@ -81,16 +82,16 @@ export function useNftMetadata(contract: string, tokenId: string): NFTResource { const key = getNftKey(contract, tokenId); - const cached = cache[key]; + const cachedData = cache[key]; useEffect(() => { - if (!cached) { + if (!cachedData || isOutdated(cachedData)) { loadNFTMetadata(contract, tokenId); } - }, [contract, tokenId, cached, loadNFTMetadata]); + }, [contract, tokenId, cachedData, loadNFTMetadata]); - if (cached) { - return cached; + if (cachedData) { + return cachedData; } else { return { status: "queued", diff --git a/src/nft/NftMetadataProvider/logic.ts b/src/nft/NftMetadataProvider/logic.ts new file mode 100644 index 0000000000..58939e8af8 --- /dev/null +++ b/src/nft/NftMetadataProvider/logic.ts @@ -0,0 +1,20 @@ +import { NFTResource } from "./types"; + +// Handle lifecycle of cached data. +// Expiration date depend on the resource's status. +export function isOutdated(resource: NFTResource): boolean { + const now = Date.now(); + + switch (resource.status) { + case "loaded": { + return now - resource.updatedAt > 14 * 24 * 60 * 60 * 1 * 1000; // 14 days + } + case "error": { + return now - resource.updatedAt > 1 * 1000; // 1 second + } + case "nodata": { + return now - resource.updatedAt > 24 * 60 * 60 * 1 * 1000; // 1 day + } + } + return false; +} diff --git a/src/nft/NftMetadataProvider/types.ts b/src/nft/NftMetadataProvider/types.ts index 15b3baeae8..935d7e1a97 100644 --- a/src/nft/NftMetadataProvider/types.ts +++ b/src/nft/NftMetadataProvider/types.ts @@ -22,6 +22,7 @@ export type NFTResourceError = { export type NFTResourceNoData = { status: "nodata"; + updatedAt: number; }; export type NFTResource =