54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import { Option, Some, None, none } from "optionals";
|
|
|
|
export function catcher<T>(f: () => T): Option<T> {
|
|
try {
|
|
return Some(f());
|
|
} catch {
|
|
// There is no need to define what is already undefined.
|
|
return None();
|
|
}
|
|
}
|
|
|
|
export async function catcher_async<T>(
|
|
f: () => Promise<T>
|
|
): Promise<Option<T>> {
|
|
try {
|
|
return Some(await f());
|
|
} catch {
|
|
return None();
|
|
}
|
|
}
|
|
|
|
export function squish_option<T>(opt: Option<Option<T>>): Option<T> {
|
|
return opt.unwrapOr(None());
|
|
}
|
|
|
|
export function json_response(obj: any, options?: ResponseInit): Response {
|
|
return new Response(JSON.stringify(obj), {
|
|
...options,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
|
|
export function fetch_json(
|
|
input: RequestInfo | URL,
|
|
init?: RequestInit
|
|
): Promise<Option<any>> {
|
|
return catcher_async(() => fetch(input, init).then(j => j.json()));
|
|
}
|
|
|
|
export function class_list(...classes: Array<string | undefined>): string {
|
|
return classes.filter(Boolean).join(" ");
|
|
}
|
|
|
|
export function remove_undefined_keys(obj: any): any {
|
|
return Object.keys(obj).reduce((acc, key) => {
|
|
if (obj[key] !== undefined && obj[key] !== "") {
|
|
acc[key] = obj[key];
|
|
}
|
|
return acc;
|
|
}, {});
|
|
}
|
|
|
|
export const URL = "https://fl.pyrope.net";
|