Last active
March 16, 2023 05:21
-
-
Save earthchie/bf6c7dcda912ed7f37c7b61aa84ccaf9 to your computer and use it in GitHub Desktop.
Snippet for parsing the NFT metadata using the Fetch API. Supports both URI and IPFS format.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function parseNFTMetadata(metadata, ipfs_gateway = 'https://ipfs.io/ipfs/'){ | |
const applyIPFSGateway = function(uri){ | |
if(uri instanceof Array){ | |
return uri.map(i=>applyIPFSGateway(i)); | |
}else if(typeof uri === 'object'){ | |
Object.keys(uri).forEach(k=>{ | |
uri[k] = applyIPFSGateway(uri[k]); | |
}); | |
return uri; | |
}else if(typeof uri === 'string'){ | |
return uri.replace('ipfs://', ipfs_gateway); | |
}else{ | |
return uri; | |
} | |
}; | |
metadata = applyIPFSGateway(metadata); | |
try{ | |
const URI = new URL(metadata); | |
return applyIPFSGateway(await (await fetch(metadata)).json()); | |
}catch(e){ | |
return metadata; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: