Skip to content

Parsing

Dillon Redding edited this page Dec 31, 2023 · 6 revisions

A requirement for any API client is parsing content from a server response. For a Siren client, you can use the parse function to transform content to an instance of an Entity.

You can use it to parse JSON text:

import { Entity, parse } from '@siren-js/client';

const siren = JSON.stringify(orderEntity); // orderEntity is from the Modeling page 👉
const sameAsOrderEntity = await parse(siren);

// specify the type of entity's `properties` using `parse`'s type parameter
const orderWithTypedProperties = await parse<OrderProperties>(siren);

You can parse a plain object with it:

const obj = JSON.parse(siren);
const theSameOrderEntity = await parse(obj);

You can even parse a Response object (e.g., after following a link or submitting an action):

const response = await fetch('http://api.x.io/orders/42');
const alsoTheOrderEntity = await parse(response);

You may want to ensure the Response has Siren content before attempting to parse.

const contentType = response.headers.get('Content-Type');
if (contentType === 'application/vnd.siren+json') {
  await parse(response);
}

Clone this wiki locally