38 lines
727 B
TypeScript
Raw Normal View History

2024-08-15 12:08:45 +02:00
import { type SafeValue } from "../values/values";
2024-08-15 12:08:15 +02:00
export const Fetch = {
2024-08-15 12:08:45 +02:00
async safe<T extends Object>(
url: string,
init: RequestInit
): Promise<SafeValue<T>> {
const res = await fetch(url, init);
2024-08-15 12:08:15 +02:00
2024-08-15 12:08:45 +02:00
if (!res.ok) {
const message = await res.text();
2024-08-15 12:08:15 +02:00
2024-08-15 12:08:45 +02:00
return {
error: true,
data: {
type: "api",
message,
status: res.status,
},
};
}
2024-08-15 12:08:15 +02:00
2024-08-15 12:08:45 +02:00
try {
const json = await res.json();
2024-08-15 12:08:15 +02:00
2024-08-15 12:08:45 +02:00
return { error: false, data: json };
} catch (e) {
return {
error: true,
data: {
type: "error",
message: e instanceof Error ? e.message : "JSON parsing error :" + e,
},
};
}
},
};