All files / services/document prefix-downloader-service.ts

100% Statements 7/7
100% Branches 2/2
100% Functions 1/1
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                          3x             3x   3x 1x     2x   2x             2x        
import defaultPrefixes from './default-prefixes.json';
 
export interface PrefixDefinitions {
	/**
	 * The date the prefixes were last updated.
	 */
	lastUpdated: Date | undefined;
 
	/**
	 * A dictionary of prefixes and their URIs.
	 */
	prefixes: { [key: string]: string };
}
 
/**
 * A service that downloads prefixes from the web.
 */
export class PrefixDownloaderService {
	/**
	 * The URL of the endpoint to download prefixes from.
	 */
	readonly endpointUrl = 'https://prefix.cc/context';
 
	/**
	 * Retrieve a dictionary of prefixes and their URIs from the web.
	 * @returns A promise that resolves to a dictionary of prefixes and their URIs.
	 */
	async fetchPrefixes(): Promise<PrefixDefinitions> {
		const response = await fetch(this.endpointUrl);
 
		if (!response.ok) {
			throw new Error(`Failed to fetch prefixes: ${response.statusText}`);
		}
 
		const data = await response.json();
 
		return {
			lastUpdated: new Date(),
			prefixes: data['@context']
		};
	}
}
 
export const DEFAULT_PREFIXES: PrefixDefinitions = {
	lastUpdated: undefined,
	prefixes: defaultPrefixes.prefixes
};