UNPKG

1.88 kBPlain TextView Raw
1import * as uriTemplate from 'uri-template';
2import { resolve } from './utils/url';
3
4type LinkInit = {
5 context: string,
6 href: string,
7 name?: string,
8 rel: string,
9 templated?: boolean,
10 title?: string,
11 type?: string,
12};
13
14/**
15 * The Link object represents a hyperlink.
16 */
17export default class Link {
18
19 /**
20 * The base href of the parent document. Used for expanding relative links.
21 */
22 context: string;
23
24 /**
25 * The URI of the link. Might be relative
26 */
27 href: string;
28
29 /**
30 * The name for a link. This might be used to disambiguate the link.
31 *
32 * If you're looking at this, chances are that you might want 'title'
33 * instead.
34 */
35 name?: string;
36
37 /**
38 * The relationship type
39 */
40 rel: string;
41
42 /**
43 * Is it a URI template or not?
44 */
45 templated: boolean;
46
47 /**
48 * A human-readable label for the link.
49 */
50 title: string | null;
51
52 /**
53 * A mimetype
54 */
55 type: string | null;
56
57 constructor(properties: LinkInit) {
58
59 this.templated = false;
60 this.title = null;
61 this.type = null;
62 for (const key of ['context', 'href', 'name', 'rel', 'templated', 'title', 'type']) {
63 if ((<any> properties)[key]) {
64 (<any> this)[key] = (<any> properties)[key];
65 }
66 }
67
68 }
69
70
71 /**
72 * Returns the absolute link url, based on it's base and relative url.
73 */
74 resolve(): string {
75
76 return resolve(this.context, this.href);
77
78 }
79
80 /**
81 * Expands a link template (RFC6570) and resolves the uri
82 *
83 * @param {object} variables - A list of variables to expand the link with.
84 * @returns {string}
85 */
86 expand(variables: object): string {
87
88 if (!this.templated) {
89 return resolve(this.context, this.href);
90 } else {
91 const templ = uriTemplate.parse(this.href);
92 const expanded = templ.expand(variables);
93 return resolve(this.context, expanded);
94 }
95
96 }
97
98}