| 1 |
import { log_error } from "../log"; |
| 2 |
import { set_mtime } from "../stores/mtime"; |
| 3 |
import { |
| 4 |
defaultValue, |
| 5 |
isJsonObject, |
| 6 |
object, |
| 7 |
string, |
| 8 |
unknown, |
| 9 |
} from "./validation"; |
| 10 |
|
| 11 |
class FetchError extends Error {} |
| 12 |
|
| 13 |
/** Wrapper around fetch with some default options */ |
| 14 |
export async function fetch( |
| 15 |
input: string, |
| 16 |
init: RequestInit = {}, |
| 17 |
): Promise<Response> { |
| 18 |
return window.fetch(input, { credentials: "same-origin", ...init }); |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* Handles JSON content for a Promise returned by fetch, also handling an HTTP |
| 23 |
* error status. |
| 24 |
*/ |
| 25 |
async function handleJSON( |
| 26 |
response: Response, |
| 27 |
): Promise<Record<string, unknown>> { |
| 28 |
const data: unknown = await response.json().catch(() => null); |
| 29 |
if (!response.ok) { |
| 30 |
throw new FetchError( |
| 31 |
isJsonObject(data) && typeof data.error === "string" |
| 32 |
? data.error |
| 33 |
: response.statusText, |
| 34 |
); |
| 35 |
} |
| 36 |
if (!isJsonObject(data)) { |
| 37 |
throw new FetchError("Invalid response: not a valid JSON object"); |
| 38 |
} |
| 39 |
return data; |
| 40 |
} |
| 41 |
|
| 42 |
const response_validator = object({ |
| 43 |
data: unknown, |
| 44 |
mtime: defaultValue(string, () => null), |
| 45 |
}); |
| 46 |
|
| 47 |
export async function fetchJSON( |
| 48 |
input: string, |
| 49 |
init?: RequestInit, |
| 50 |
): Promise<unknown> { |
| 51 |
const res = await fetch(input, init).then(handleJSON); |
| 52 |
const validated = response_validator(res).unwrap_or(null); |
| 53 |
if (validated) { |
| 54 |
if (typeof validated.mtime === "string") { |
| 55 |
set_mtime(validated.mtime); |
| 56 |
} |
| 57 |
return validated.data; |
| 58 |
} |
| 59 |
log_error(res); |
| 60 |
throw new FetchError("Invalid response: missing data or mtime key."); |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Handles text content for a Promise returned by fetch, also handling an HTTP |
| 65 |
* error status. |
| 66 |
*/ |
| 67 |
export async function handleText(response: Response): Promise<string> { |
| 68 |
if (!response.ok) { |
| 69 |
const msg = await response.text().catch(() => response.statusText); |
| 70 |
throw new FetchError(msg); |
| 71 |
} |
| 72 |
return response.text(); |
| 73 |
} |