Skip to content
This repository has been archived by the owner on Jul 15, 2022. It is now read-only.

Commit

Permalink
added expiration logic
Browse files Browse the repository at this point in the history
  • Loading branch information
IAmMorrow authored and lambertkevin committed Nov 4, 2021
1 parent d9c81ff commit 608c951
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/nft/NftMetadataProvider/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
NFTMetadataContextType,
NFTResource,
} from "./types";
import { isOutdated } from "./logic";

const currency: Currency = findCryptoCurrencyById("ethereum")!;
const ethApi: API = apiForCurrency(currency);
Expand Down Expand Up @@ -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",
Expand Down
20 changes: 20 additions & 0 deletions src/nft/NftMetadataProvider/logic.ts
Original file line number Diff line number Diff line change
@@ -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;
}
1 change: 1 addition & 0 deletions src/nft/NftMetadataProvider/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export type NFTResourceError = {

export type NFTResourceNoData = {
status: "nodata";
updatedAt: number;
};

export type NFTResource =
Expand Down

0 comments on commit 608c951

Please sign in to comment.