2022-09-03 06:51:57 +00:00
|
|
|
interface Options {
|
|
|
|
notFoundOk: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function jsonFetcher<T>(url: string, options: Options = { notFoundOk: true}): Promise<T | null> {
|
2022-03-18 05:06:20 +00:00
|
|
|
const res = await fetch(url);
|
|
|
|
|
|
|
|
if (!res.ok) {
|
2022-09-03 06:51:57 +00:00
|
|
|
if (res.status === 404 && options.notFoundOk) {
|
2022-03-18 05:06:20 +00:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
const error = new Error("An error occurred while fetching the data.");
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
|
|
|
return res.json();
|
|
|
|
};
|
|
|
|
|
2022-09-03 06:51:57 +00:00
|
|
|
export async function jsonFetcherWithLastModified<T>(url: string, options: Options = { notFoundOk: true}): Promise<{ data: T, lastModified: string | null } | null> {
|
2022-03-18 05:06:20 +00:00
|
|
|
const res = await fetch(url);
|
|
|
|
|
|
|
|
if (!res.ok) {
|
2022-09-03 06:51:57 +00:00
|
|
|
if (res.status === 404 && options.notFoundOk) {
|
2022-03-18 05:06:20 +00:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
const error = new Error("An error occurred while fetching the data.");
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
lastModified: res.headers.get("Last-Modified"),
|
|
|
|
data: await res.json(),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function csvFetcher(url: string): Promise<string> {
|
|
|
|
return (await fetch(url)).text();
|
|
|
|
}
|