Link helper
The JavaScript SDK has a link helper to build and parse REST API URLs.
This article only covers one example, but it is similar for all links. See the API reference for a complete overview.
First we explain how link parsing and building works, followed by how the link helper can work with that.
Links
Link objects represent a link to a resource using the Hypertext Application Language (HAL) format.
Links can be templated, which means they contain variables that need to be bound before the link is useful. For example, the Link object that is a template to an entity looks like this:
Template = true
Title = "Get the entity with the specified id"
Uri = "http://contenthub_url/api/entities/{id}{?culture,members,groups,renditions,nestedRelations,loadPermissions}"
This template can be fetched like this:
import { ApiRoutesDictionary } from "@sitecore/sc-contenthub-webclient-sdk/dist/api/api-routes-dictionary";
import Link from "@sitecore/sc-contenthub-webclient-sdk/dist/link";
var routes: ApiRoutesDictionary = await client.api.getApiRoutesAsync();
var entityByIdTemplate: Link = routes["entity_by_id"];
Where used Constants.Api.EntityById.TemplateName is just "entity_by_id".
Manually parsing links
Parsing the URL we just created can be done using the getVariableValue method of the Uri class. This also needs the Link template from before. The result of this method will be "1000", which matches what was filled in by the previous section.
import Link from "@sitecore/sc-contenthub-webclient-sdk/dist/link";
import { ApiRoutesDictionary } from "@sitecore/sc-contenthub-webclient-sdk/dist/api/api-routes-dictionary";
var routes: ApiRoutesDictionary = await client.api.getApiRoutesAsync();
var entityByIdTemplate: Link = routes["entity_by_id"];
var link = new Link("http://contenthub_url/api/entities/1000")
var id: string = link.getVariableValue(entityByIdTemplate, "id");
Building links
Manually parsing and building links can be tedious, so it is best to leave it to the link helper.
The following snippet constructs a link object to the entity with an ID of 1000.
import Link from "@sitecore/sc-contenthub-webclient-sdk/dist/link";
var entityLink: Link = await client.linkHelper.entityToLinkAsync(entityId);
If the JavaScript SDK is connected to contenthub_url , then entityLink.Uri will point to contenthub_url/api/entities/1000.
Parsing links
If only the entity ID is to be returned from an entity link, then use the following snippet:
var entityId : number = await client.linkHelper.idFromEntityAsync(entityLink);
If passing the link that was created earlier, then the result will be 1000.