What is the best way to distinguish between an IPFS URL or path (content-addressed) and a regular URL (location-addressed)?

I need to retrieve nft-metadata for the nfts that have been added to my platform. Some of these Nfts have ipfs-urls as their tokenURIs and I am looking for a way to distinguish them from regular urls (location-addressed urls).

Previously, I used is-ipfs, but it was returning false even for valid ipfs-urls!

if (mtokenUri) {
  var res;
  var data;

  console.log("### ipfs url check ###");
  console.log(
    isIPFS.urlOrPath(
      "ipfs://bafybeihbsysdkemc3kyylegtfopkrcfiih4exnasoql2q36fb4zawlrwhy/volcano.json",
    ),
  );
  // false for "ipfs://bafybeihbsysdkemc3kyylegtfopkrcfiih4exnasoql2q36fb4zawlrwhy/volcano.json"

  //this is not very reliable
  if (isIPFS.urlOrPath(mtokenUri)) {
    //gives false even for a valid ipfs-url
    console.log("inside erc721 ipfs: ");

    isIpfsUrl = true;
    console.log("*** 721 isIpfs url ***");
    console.log(isIPFS.urlOrPath(mtokenUri));
    // example ccid = 'QmPzhc9ezphJ85qJWfVVpeHkPieDJznpYduGhMYD7Z4Ac9'
    const cid_eg2 =
      "bafybeihbsysdkemc3kyylegtfopkrcfiih4exnasoql2q36fb4zawlrwhy/volcano.json";
    try {
      res = await ipfs.cat(mtokenUri);
      // data = await res.json()
      console.log(res);
    } catch (error) {
      console.log(error);
    }

    //shows:cat {<suspended>}
  } else {
    //do normal fetch

    try {
      res = await fetch(mtokenUri);
      data = await res.json();

      console.log("erc721 normal fetch");
      console.log("*** Normal fetch data *** ");

      console.log(data);
      _imageUrl = data.image;
      _name = data.name;
      _description = data.description;
    } catch (error) {
      console.log(error);
    }
  }
}

When I attempt to fetch an ipfs-url using 'fetch', it displays-

https://i.sstatic.net/VmbF0.png

Is there a more effective/reliable way to accomplish this?

Answer №1

Shoutout to @AKX for the valuable contribution. Currently utilizing the following approach-

  if (
      isIPFS.urlOrPath(theUri) ||
      mtokenUri.startsWith('ipfs://') ||
      mtokenUri.includes('/ipfs/') ||
      mtokenUri.includes('/bafy')
     ) { 
       // extracting or combining ipfs-url
       } else { 
        // parsing or retrieving regular non-ipfs-url
       }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Generate a JSON Object array by collecting data from various elements to make it dynamic

Seeking assistance in creating a dynamic array of JSON objects from the values of various elements. Below are some examples of these elements. There are more elements contributing to the JSON values, but I don't want to repeat the same code three time ...

Discover the specific item within an array of objects

Anyone have information like this: const info = { Title : "Banana", Quantity : 10, Location : "Everywhere", Phone : 123456, A : 987, B : 654, } and there is another array of details as: const dataArr = ["Title",&q ...

Rule: attribute should indicate a specific function

I am currently trying to implement the functionality from https://github.com/rpocklin/angular-scroll-animate in my project, but I keep encountering an error in my console: Error: Directive: angular-scroll-animate 'when-visible' attribute must ...

Insert a fresh row into the gridview using JavaScript

I am working with a grid view where I dynamically add new rows using JavaScript. Each row in the grid view contains an image (addButton), which triggers a specific JavaScript function when clicked. function AddNewRecord(e) { debugger; var hfFirst ...

When using json_decode with $_POST, it may return NULL

Having difficulty with json_decode and a valid JSON being sent via $_POST. Here's the JSON object, stored in the "inventory" variable: [{"item_name":"Screw Driver","item_desc":"asdasd","item_type":"weapon"}, {"item_name":"Brown Shoes","item_desc": ...

Is it better to have JavaScript and HTML in separate files or combined into a single HTML file?

Do you notice any difference when coding in both HTML and JavaScript within a single .html file compared to separating HTML code in a .html file and JavaScript code in a .js file? Does the functionality remain the same in both scenarios? For example, in t ...

What is the best way to incorporate a dropdown header in Material-UI on a React project?

I am facing an issue where only the last Menu Dropdown is rendering, but I actually need different Menus to be displayed (with the text faintly appearing behind them). I am uncertain about how to correctly pass the props/state to make this work. import Rea ...

Integrate user interface functionality within the server component in NextJS

When considering the Server Component located in the new app/ directory within NextJS: export default async function RootLayout({ children }) { const categories = await getCategories(); // const [navigation, setNavigation] = React.useState('hidde ...

Information has been extracted from the source, however, no content is being shown

Recently, I developed a web application with an AngularJS frontend and Rails backend. I uploaded my frontend code to JSFIDDLE. Meanwhile, the rails backend on the index page is returning some JSON: [{"id":1,"name":null,"user_id":null,"created_at":"2013-1 ...

Semantic UI (React): Transforming vertical menu into horizontal layout for mobile responsiveness

I have implemented a vertical menu using Semantic UI React. Here is the structure of my menu: <Grid> <Grid.Column mobile={16} tablet={5} computer={5}> <div className='ui secondary pointing menu vertical compact inherit&apos ...

Twitter typeahead not functioning properly when used in conjunction with ajax requests

I have limited experience in the frontend world and I'm currently working on getting this to function properly. $('#the-basics .typeahead').typeahead({ hint: true, highlight: true, minLength: 6 }, { source: function (query, ...

the click event fails to trigger when the id or class is modified

Hey there, I'm new to working with jquery and I've encountered a problem. Here's the code snippet: http://jsfiddle.net/8guzD/ $('#test.off').click(function(){ $(this).removeClass('off').addClass('on'); }) ...

iOS - Embedding text into a UIWebView input field

Just a quick question - if a textfield in a webform does not automatically have the focus set by the form, meaning you have to press the field before the keyboard pops up, am I correct in assuming that the field cannot be edited? In simpler terms - is it ...

Guide to adding a file upload progress bar to your website

Is there a way to enhance file upload experience on my web application beyond the usual animated gif? I'm currently using .Net, but open to platform agnostic solutions as well. ...

Develop a unique method for loading AngularJS templates

When working with AngularJS, there are various ways to provide an external template, such as using a script tag or a separate HTML file on the web server. However, I am faced with a situation where I need to implement a custom logic for retrieving these ...

JavaScript: Launching the current page in a new tab or window

Is it feasible to open a new window or tab from the existing HTML page? Absolutely, I am referring to the current HTML page itself. Not triggered by an external call like this: window.open('page.html', '_blank'); Possible through Jav ...

Interact with AJAX form to dynamically display result data in the intended DIV

Seeking assistance from experienced JS users! Although most features are functional, including results being returned and forms submitting to MC database, I am encountering an issue where the result html is appearing in the incorrect DIV. Instead of displ ...

Learn how to successfully place a draggable object into a sortable container while ensuring that the dropped item is a personalized helper element rather than the original object

The jQuery draggable/sortable demo showcases the process of dropping a clone of the draggable item (both draggable and sortable elements share the same structure). However, I am interested in dropping a different DOM structure. For example, when dragging a ...

Is it possible to modify this code to accept multiple IDs at once?

I'm attempting to create a form in JavaScript where, upon entering the necessary details and clicking submit, the user's email client opens with the information pre-filled for easy sending. However, I am facing challenges as my code involves mult ...