UNPKG

ketting

Version:

Opinionated HATEOAS / Rest client.

121 lines 3.18 kB
import { resolve } from './util/uri.js'; /** * Links container, providing an easy way to manage a set of links. */ export class Links { defaultContext; store; 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 { 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 = { 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 = resolve(this.defaultContext, href); this.store.set(rel, uris.filter(uri => 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); } } /** * The LinkNotFound error gets thrown whenever something tries to follow a * link by its rel, that doesn't exist */ export class LinkNotFound extends Error { } //# sourceMappingURL=link.js.map