Translate HATEOAS HAL links into URLs that can be used by your application trough one method. Handles missing links and translation of templated link options into query string parameters.
It is fully compatible with Spring Data Rest HAL layer.
npm install hateoas-hal-link-resolverResolver is written for EcmaScript modules, so after installing you are one step from using it.
import resolve from 'hateoas-hal-link-resolver';This defined user object will be a base for all of our examples.
const user = {
name: 'The Doctor',
_links: {
self: 'https://example.com/characters/1',
companions: {
href: 'https://example.com/characters/1/companions{?page,size}',
templated: true,
},
enemies: [
{
href: 'https://example.com/characters/1/enemies{?race,page,size}',
templated: true,
},
{
href: 'https://example.com/characters/1/enemies{?nameSearch,page,size}',
templated: true,
},
{
href: 'https://example.com/characters/1/enemies?noParams',
templated: false,
},
],
},
};resolve(user._links, 'self');
// https://example.com/characters/1When you pass no parameters, the link template will be simply stripped of options. Based on top example.
resolve(user._links, 'companions');
// https://example.com/characters/1/companionsWhen you pass parameters, they will be translated into the link template options. Based on top example.
resolve(user._links, 'companions', {
page: 3,
size: 5,
});
// https://example.com/characters/1/companions?page=3&size=5Beware, all parameters that have no matching link option will get lost. Based on top example.
resolve(user._links, 'companions', {
page: 3,
filter: 'Bad Wolf',
});
// https://example.com/characters/1/companions?page=3The resolver will choose the best link for you based on the list of parameters you provide. If you provide none, then the non-templated links are preferred. Based on top example.
resolve(user._links, 'enemies');
// Returns the non-templated link
// https://example.com/characters/1/enemies?noParamsresolve(user._links, 'enemies', {
race: 'timelord',
});
// https://example.com/characters/1/enemies?race=timelordIt may happen that you provide parameters that are mutually exclusive by the links definition. In that case, resolver will give you the first link specified. In the top example, we cannot search by name and race at the same time.
resolve(user._links, 'enemies', {
race: 'timelord',
nameSearch: 'The Master',
page: 10,
size: 5,
});
// https://example.com/characters/1/enemies?race=timelord&page=10&size=5If your API uses _links or links to provide HAL links, you can simply pass the object to get branch shortcut.
resolve(user, 'self');
// https://example.com/characters/1Query String Manipulator used as dependency in this project for quick and easy URL query transformations.