2

I need to get an image URL from Contentful entry id. I am getting such an JSON from Contentful query

{
"sys":{
  "space":{
     "sys":{
        "type":"Link",
        "linkType":"Space",
        "id":"8v1e7eaw70p2"
     }
  },
  "id":"1JfEwVlD9WmYikE8kS8iCA",
  "type":"Entry",
  "createdAt":"2018-02-28T18:50:08.758Z",
  "updatedAt":"2018-02-28T18:50:08.758Z",
  "revision":1,
  "contentType":{
     "sys":{
        "type":"Link",
        "linkType":"ContentType",
        "id":"image"
     }
  },
  "locale":"en-US"
},
"fields":{
  "name":"heat",
  "image":{
     "sys":{
        "type":"Link",
        "linkType":"Asset",
        "id":"6Inruq2U0M2kOYsSAu8Ywk"
     }
  }
}
}

I am using JS driver they provide:

client.getEntry()

so how to go thru that link: 6Inruq2U0M2kOYsSAu8Ywk ?

3 Answers3

4

Unfortunately, the js SDK will not be able to resolve links when using the single entry endpoint i.e client.getEntry() because there won't be enough data.

When thing I always recommend to work around this is to use the collection endpoint with a query the desired id as a query param. This way you will always get the desired entry with all it's linked data. Your code should look something like this

client.getEntries({'sys.id': '6Inruq2U0M2kOYsSAu8Ywk'})
  .then(response => console.log(response.items[0].fields.image.fields.file.url))

I hope that helps. Best, Khaled

Khaled Garbaya
  • 1,479
  • 16
  • 20
0

Use client.getEntries({'sys.id': '1JfEwVlD9WmYikE8kS8iCA'}) To get the entry fields and the asset fields.

You can also patch the assets to the fields by running this after fetching the data:

/* Patch all the assets to the fields */
  const patchAssets = (fields, assets) => {
    Object.keys(fields).forEach(function (key) {
      let obj = fields[key];
      if (obj.sys && obj.sys.linkType === 'Asset') {
        const assetId = obj.sys.id;
        const matchAsset = assets.find(asset => {
          return asset.id === assetId;
        });
        obj.file = matchAsset;
      }
    });
    return fields;
  };
Linx8
  • 64
  • 4
0

Another way to get image url is to use getAsset('<asset_id>'). So first, using the getEntry() method, you need to get the entry data, then extract the id from the field: fields.image.sys.id, and pass it to the getAsset method.

drazewski
  • 1,739
  • 1
  • 19
  • 21