UNPKG

2.83 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.LinkNotFound = exports.Links = void 0;
4/**
5 * Links container, providing an easy way to manage a set of links.
6 */
7class Links {
8 constructor(defaultContext, links) {
9 this.defaultContext = defaultContext;
10 this.store = new Map();
11 if (links) {
12 if (links instanceof Links) {
13 this.add(...links.getAll());
14 }
15 else {
16 for (const link of links) {
17 this.add(link);
18 }
19 }
20 }
21 }
22 add(...args) {
23 let links;
24 if (typeof args[0] === 'string') {
25 links = [{
26 rel: args[0],
27 href: args[1],
28 context: this.defaultContext,
29 }];
30 }
31 else {
32 links = args.map(link => { return Object.assign({ context: this.defaultContext }, link); });
33 }
34 for (const link of links) {
35 if (this.store.has(link.rel)) {
36 this.store.get(link.rel).push(link);
37 }
38 else {
39 this.store.set(link.rel, [link]);
40 }
41 }
42 }
43 set(arg1, arg2) {
44 let link;
45 if (typeof arg1 === 'string') {
46 link = {
47 rel: arg1,
48 href: arg2,
49 context: this.defaultContext,
50 };
51 }
52 else {
53 link = Object.assign({ context: this.defaultContext }, arg1);
54 }
55 this.store.set(link.rel, [link]);
56 }
57 /**
58 * Return a single link by its 'rel'.
59 *
60 * If the link does not exist, undefined is returned.
61 */
62 get(rel) {
63 const links = this.store.get(rel);
64 if (!links || links.length < 0) {
65 return undefined;
66 }
67 return links[0];
68 }
69 /**
70 * Delete all links with the given 'rel'.
71 */
72 delete(rel) {
73 this.store.delete(rel);
74 }
75 /**
76 * Return all links that have a given rel.
77 *
78 * If no links with the rel were found, an empty array is returned.
79 */
80 getMany(rel) {
81 return this.store.get(rel) || [];
82 }
83 /**
84 * Return all links.
85 */
86 getAll() {
87 const result = [];
88 for (const links of this.store.values()) {
89 result.push(...links);
90 }
91 return result;
92 }
93 /**
94 * Returns true if at least 1 link with the given rel exists.
95 */
96 has(rel) {
97 return this.store.has(rel);
98 }
99}
100exports.Links = Links;
101/**
102 * The LinkNotFound error gets thrown whenever something tries to follow a
103 * link by its rel, that doesn't exist
104 */
105class LinkNotFound extends Error {
106}
107exports.LinkNotFound = LinkNotFound;
108//# sourceMappingURL=link.js.map
\No newline at end of file