66 lines
1.7 KiB
TypeScript
66 lines
1.7 KiB
TypeScript
import { VideoList } from './datatypes/VideoList';
|
|
import { VideoOnDemandIndex } from './datatypes/VideoOnDemandIdentifier';
|
|
|
|
const upstreamURL = process.env.UPSTREAM_URL;
|
|
const upstreamDirectURL = process.env.UPSTREAM_DIRECT_URL || upstreamURL;
|
|
// const apiURL = process.env.API_URL || `${upstreamURL}/api`;
|
|
const apiDirectURL = process.env.API_DIRECT_URL || `${upstreamDirectURL}/api`;
|
|
|
|
export class HTTPError extends Error {
|
|
response: Response;
|
|
|
|
data: any;
|
|
|
|
constructor(response: Response, data: any) {
|
|
super(`HTTP server responded with error: ${response.statusText}`);
|
|
|
|
this.response = response;
|
|
this.data = data;
|
|
}
|
|
}
|
|
|
|
export async function fetchJson(
|
|
input: RequestInfo,
|
|
init?: RequestInit,
|
|
) {
|
|
try {
|
|
const response = await fetch(input, init);
|
|
|
|
// if the server replies, there's always some data in json
|
|
// if there's a network error, it will throw at the previous line
|
|
const data = await response.json();
|
|
|
|
if (response.ok) {
|
|
return data;
|
|
}
|
|
|
|
throw new HTTPError(response, data);
|
|
} catch (error) {
|
|
if (!error.data) {
|
|
error.data = { message: error.message };
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function getDirect(relativeURL: string) {
|
|
return fetchJson(`${apiDirectURL}/${relativeURL}`);
|
|
}
|
|
|
|
// async function get(relativeURL: any) {
|
|
// return fetchJson(`${apiURL}/${relativeURL}`);
|
|
// }
|
|
|
|
export async function getIndex(): Promise<VideoOnDemandIndex> {
|
|
return getDirect('index.json');
|
|
}
|
|
|
|
export async function getVideos(id: string): Promise<VideoList> {
|
|
return getDirect(`videos/${id}.json`);
|
|
}
|
|
|
|
export function getDownloadURL(id: string, fileName: string): string {
|
|
return [upstreamURL, encodeURIComponent(id), encodeURIComponent(fileName)]
|
|
.join('/');
|
|
}
|