Skip to content

Instantly share code, notes, and snippets.

@earthchie
Last active March 16, 2023 05:21
Show Gist options
  • Save earthchie/bf6c7dcda912ed7f37c7b61aa84ccaf9 to your computer and use it in GitHub Desktop.
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.
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;
}
}
@earthchie
Copy link
Author

earthchie commented Jan 10, 2023

Example:

console.log('from standard URI', await parseNFTMetadata('data:application/json,%7B%22name%22%3A%22ThaiChain%20-%20Early%20Miner%20Certificate%22%2C%22description%22%3A%22The%20owner%20of%20this%20NFT%20has%20mined%20JIB%20Chain%20since%202022!%20Thanks%20for%20being%20a%20part%20of%20the%20community.%22%2C%22image%22%3A%22ipfs%3A%2F%2FQmVyBhfd2YS9MWgnWi3jDiPpGQ5zv59GLFNsMVwK7YH1kE%22%2C%22url%22%3A%22https%3A%2F%2Fipfs.8api.sh%2Fipfs%2FQmVyBhfd2YS9MWgnWi3jDiPpGQ5zv59GLFNsMVwK7YH1kE%22%7D'));

console.log('from base64 URI', await parseNFTMetadata('data:application/json;base64,eyJuYW1lIjogIkJhZyAjMTE0MzgyMSIsICJkZXNjcmlwdGlvbiI6ICJNb3JlIExvb3QgaXMgYWRkaXRpb25hbCByYW5kb21pemVkIGFkdmVudHVyZXIgZ2VhciBnZW5lcmF0ZWQgYW5kIHN0b3JlZCBvbiBjaGFpbi4g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Z2VUMGlPREFpSUdOc1lYTnpQU0ppWVhObElqNGlSV0ZuYkdVZ1RXOXZiaUlnVUd4aGRHVmtJRUpsYkhRZ2IyWWdWbWwwY21sdmJDQXJNVHd2ZEdWNGRENDhkR1Y0ZENCNFBTSXhNQ0lnZVQwaU1UQXdJaUJqYkdGemN6MGlZbUZ6WlNJK1NHRnlaQ0JNWldGMGFHVnlJRUp2YjNSelBDOTBaWGgwUGp4MFpYaDBJSGc5SWpFd0lpQjVQU0l4TWpBaUlHTnNZWE56UFNKaVlYTmxJajRpU0dGMmIyTWdWMmhwYzNCbGNpSWdSR2wyYVc1bElFZHNiM1psY3lCdlppQkZibXhwWjJoMFpXNXRaVzUwUEM5MFpYaDBQangwWlhoMElIZzlJakV3SWlCNVBTSXhOREFpSUdOc1lYTnpQU0ppWVhObElqNUJiWFZzWlhROEwzUmxlSFErUEhSbGVIUWdlRDBpTVRBaUlIazlJakUyTUNJZ1kyeGhjM005SW1KaGMyVWlQaUpOYVc1a0lFSnBkR1VpSUZOcGJIWmxjaUJTYVc1bklHOW1JSFJvWlNCR2IzZ2dLekU4TDNSbGVIUStQQzl6ZG1jKyJ9'));

console.log('from Cloudflare IPFS Gateway', await parseNFTMetadata('ipfs://bafybeighthknbo2hljatjaghltzy4lrisszfhrrbuo36g6r6ts2kwqiz6e/1.json'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment