| 1 | // The network, as one small thing that can be replaced. |
| 2 | // |
| 3 | // Every module that talks to the server takes one of these rather than |
| 4 | // calling fetch, so a unit test hands in a fake and never opens a socket. |
| 5 | // That is the JS discipline this repo enforces: storage and network passed |
| 6 | // in, never reached for. |
| 7 | |
| 8 | export class RequestError extends Error { |
| 9 | constructor(message, status) { |
| 10 | super(message); |
| 11 | this.status = status; |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | async function send(method, path, body) { |
| 16 | const init = { method, headers: {} }; |
| 17 | if (body !== undefined) { |
| 18 | init.headers["Content-Type"] = "application/json"; |
| 19 | init.body = JSON.stringify(body); |
| 20 | } |
| 21 | const res = await fetch(path, init); |
| 22 | if (res.status === 204) return null; |
| 23 | |
| 24 | const data = await res.json().catch(() => ({})); |
| 25 | if (!res.ok) { |
| 26 | throw new RequestError(data.error || `${method} ${path} failed`, res.status); |
| 27 | } |
| 28 | return data; |
| 29 | } |
| 30 | |
| 31 | export const net = { |
| 32 | get: (path) => send("GET", path), |
| 33 | post: (path, body) => send("POST", path, body ?? {}), |
| 34 | put: (path, body) => send("PUT", path, body ?? {}), |
| 35 | }; |
| 36 | |