cosmicjs / cosmic-sdk-js

The official JavaScript SDK for Cosmic. Use it to power content server-side, in the browser, and in native apps.
https://www.npmjs.com/package/@cosmicjs/sdk
MIT License
14 stars 2 forks source link

Fetch more media data #38

Closed tonyspiro closed 2 weeks ago

tonyspiro commented 1 month ago

What's new

Includes a new options chain method to add the full media to the Objects payload on all metadata fields. This enables easier use of alt_text, metadata and other helpful media data.

Before

So instead of this:

const { object } = await cosmic.objects
  .findOne({
    type: 'shows',
    slug: 'sf-car-show',
  })
  .props('slug,title,metadata')
  .depth(1)

Which returns:

{
  "slug": "sf-car-show",
  "title": "SF Car Show",
  "metadata": {
    "first_car": {
      "url": "https://cdn.cosmicjs.com/04ba2480-dc6c-11ed-bc7a-55cf2d59d704-FrB66Vzuxxc.jpg",
      "imgix_url": "https://imgix.cosmicjs.com/04ba2480-dc6c-11ed-bc7a-55cf2d59d704-FrB66Vzuxxc.jpg"
    },
    "second_car": {
      "url": "https://cdn.cosmicjs.com/00cd0bd0-dc6c-11ed-bc7a-55cf2d59d704-WTN4tbNtNQ.jpg",
      "imgix_url": "https://imgix.cosmicjs.com/00cd0bd0-dc6c-11ed-bc7a-55cf2d59d704-WTN4tbNtNQ.jpg"
    }
  }
}

With this update

You can now do:

const { object } = await cosmic.objects
  .findOne({
    type: 'vehicles',
    slug: 'ferrari',
  })
  .props('slug,title,metadata')
  .depth(1)
  .options({
    media: {
      props: "alt_text" // all | alt_text | name | id ... etc see media model for all available props https://www.cosmicjs.com/docs/api/media#the-media-model
    }
});

Returning all available media data:

{
  "slug": "sf-car-show",
  "title": "SF Car Show",
  "metadata": {
    "first_car": {
      "url": "https://cdn.cosmicjs.com/04ba2480-dc6c-11ed-bc7a-55cf2d59d704-FrB66Vzuxxc.jpg",
      "imgix_url": "https://imgix.cosmicjs.com/04ba2480-dc6c-11ed-bc7a-55cf2d59d704-FrB66Vzuxxc.jpg",
      "alt_text": "Gray Lambo"
    },
    "second_car": {
      "url": "https://cdn.cosmicjs.com/00cd0bd0-dc6c-11ed-bc7a-55cf2d59d704-WTN4tbNtNQ.jpg",
      "imgix_url": "https://imgix.cosmicjs.com/00cd0bd0-dc6c-11ed-bc7a-55cf2d59d704-WTN4tbNtNQ.jpg",
      "alt_text": "Red Ferarri"
    }
  }
}

How it works under the hood

  1. After calling the API for Objects, it checks the metadata response for any url or imgix_url properties.
  2. Then it collects all of the file names (mapped to the object key)
  3. Then it queries all of the names using the media.find method and the intended props declared in the options.
  4. Then it maps the values back to the Object.

Note: this will use another API request media data for each object and may slow down the response time.

tonyspiro commented 2 weeks ago

Merged with #40