1
Fork 0
href-plus/source/ts/utilities/relation-link.ts

39 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

2021-12-30 22:40:57 +00:00
// Because the MusicBrainz API doesn't return a name or label for a link, like
// for example {"name": "Bandcamp", "url": "https://bandcamp.com/..."}, we have
// to figure out a name for each link. So all the known links are simply saved
// in a JSON file where we have a regular expression to test for and a
// replacement name to use instead. And whenever a link isn't matched to any we
// can just use the host name of the URL like "bandcamp.com".
import knownLinks from './known-links.json';
type KnownLink = {
2022-01-09 13:01:04 +00:00
icon: string | undefined;
2021-12-30 22:40:57 +00:00
regex: RegExp;
text: string;
};
const known: KnownLink[] = knownLinks.map((data: Record<string, unknown>) => ({
2022-01-09 13:01:04 +00:00
icon: data.icon as string | undefined,
regex: new RegExp(data.regex as string),
text: data.text as string,
2021-12-30 22:40:57 +00:00
}));
export default class RelationLink {
2022-01-09 13:01:04 +00:00
public readonly icon: string | undefined;
public readonly isKnown: boolean;
2021-12-30 22:40:57 +00:00
public readonly link: URL;
public readonly original: string;
public readonly text: string;
constructor(relationUrl: string) {
this.original = relationUrl;
this.link = new URL(relationUrl);
const knownLink = known.find(({regex}) => regex.test(this.link.host));
2022-01-09 13:01:04 +00:00
this.icon = knownLink?.icon;
this.isKnown = knownLink !== undefined;
2021-12-30 22:40:57 +00:00
this.text = knownLink?.text ?? this.link.host;
}
}