ketting
Version:
Opiniated HATEAOS / Rest client.
121 lines • 3.3 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LinkNotFound = exports.Links = void 0;
const uri_1 = require("./util/uri");
/**
* Links container, providing an easy way to manage a set of links.
*/
class Links {
constructor(defaultContext, links) {
this.defaultContext = defaultContext;
this.store = new Map();
if (links) {
if (links instanceof Links) {
this.add(...links.getAll());
}
else {
for (const link of links) {
this.add(link);
}
}
}
}
add(...args) {
let links;
if (typeof args[0] === 'string') {
links = [{
rel: args[0],
href: args[1],
context: this.defaultContext,
}];
}
else {
links = args.map(link => { return Object.assign({ context: this.defaultContext }, link); });
}
for (const link of links) {
if (this.store.has(link.rel)) {
this.store.get(link.rel).push(link);
}
else {
this.store.set(link.rel, [link]);
}
}
}
set(arg1, arg2) {
let link;
if (typeof arg1 === 'string') {
link = {
rel: arg1,
href: arg2,
context: this.defaultContext,
};
}
else {
link = Object.assign({ context: this.defaultContext }, arg1);
}
this.store.set(link.rel, [link]);
}
/**
* Return a single link by its 'rel'.
*
* If the link does not exist, undefined is returned.
*/
get(rel) {
const links = this.store.get(rel);
if (!links || links.length < 0) {
return undefined;
}
return links[0];
}
/**
* Delete all links with the given 'rel'.
*
* If the second argument is provided, only links that match the href will
* be removed.
*/
delete(rel, href) {
if (href === undefined) {
this.store.delete(rel);
return;
}
const uris = this.store.get(rel);
if (!uris)
return;
this.store.delete(rel);
const absHref = uri_1.resolve(this.defaultContext, href);
this.store.set(rel, uris.filter(uri => uri_1.resolve(uri) !== absHref));
}
/**
* Return all links that have a given rel.
*
* If no links with the rel were found, an empty array is returned.
*/
getMany(rel) {
return this.store.get(rel) || [];
}
/**
* Return all links.
*/
getAll() {
const result = [];
for (const links of this.store.values()) {
result.push(...links);
}
return result;
}
/**
* Returns true if at least 1 link with the given rel exists.
*/
has(rel) {
return this.store.has(rel);
}
}
exports.Links = Links;
/**
* The LinkNotFound error gets thrown whenever something tries to follow a
* link by its rel, that doesn't exist
*/
class LinkNotFound extends Error {
}
exports.LinkNotFound = LinkNotFound;
//# sourceMappingURL=link.js.map