Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Magic: return NFT collection icon #197

Merged
merged 1 commit into from Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 14 additions & 7 deletions functions/common.js
Expand Up @@ -86,18 +86,24 @@ export async function viewCall({ contractId, method, args }) {

export async function nftToImageUrl({ contractId, tokenId }) {
const [token, nftMetadata] = await Promise.all([
viewCall({
contractId,
method: "nft_token",
args: { token_id: tokenId },
}),
tokenId
? viewCall({
contractId,
method: "nft_token",
args: { token_id: tokenId },
})
: Promise.resolve(null),
viewCall({
contractId,
method: "nft_metadata",
args: {},
}),
]);

if (!tokenId) {
return nftMetadata.icon;
}

const tokenMetadata = token?.metadata || {};
const tokenMedia = tokenMetadata.media || "";

Expand Down Expand Up @@ -146,12 +152,13 @@ export async function internalImageToUrl(env, image) {
try {
const { contractId, tokenId } = image.nft;
const NftKV = env.NftKV;
const path = tokenId ? `${contractId}/${tokenId}` : contractId;

let imageUrl = await NftKV.get(`${contractId}/${tokenId}`);
let imageUrl = await NftKV.get(path);
if (!imageUrl) {
imageUrl = await nftToImageUrl({ contractId, tokenId });
if (imageUrl) {
await NftKV.put(`${contractId}/${tokenId}`, imageUrl);
await NftKV.put(path, imageUrl);
}
}
return imageUrl;
Expand Down
2 changes: 1 addition & 1 deletion functions/magic/img/nft/[[index]].js
Expand Up @@ -3,7 +3,7 @@ import { internalImageToUrl } from "../../../common";
export async function onRequest({ request, next, env }) {
const url = new URL(request.url);
const parts = url.pathname.split("/");
if (parts.length !== 6) {
if (parts.length !== 5 && parts.length !== 6) {
return next();
}
const contractId = parts[4];
Expand Down