(method: string, path: string, body?: unknown)
| 25 | } |
| 26 | |
| 27 | private async request<T>(method: string, path: string, body?: unknown): Promise<T> { |
| 28 | const headers: Record<string, string> = { "Content-Type": "application/json" }; |
| 29 | if (this.token) headers["Authorization"] = `Bearer ${this.token}`; |
| 30 | |
| 31 | const resp = await fetch(`${this.baseURL}${path}`, { |
| 32 | method, |
| 33 | headers, |
| 34 | body: body ? JSON.stringify(body) : undefined, |
| 35 | }); |
| 36 | |
| 37 | // Token refresh on 401 |
| 38 | if (resp.status === 401 && this.credentials) { |
| 39 | await this.login(this.credentials.email, this.credentials.password); |
| 40 | headers["Authorization"] = `Bearer ${this.token}`; |
| 41 | const retry = await fetch(`${this.baseURL}${path}`, { |
| 42 | method, |
| 43 | headers, |
| 44 | body: body ? JSON.stringify(body) : undefined, |
| 45 | }); |
| 46 | if (!retry.ok) throw new Error(`API ${method} ${path} failed (${retry.status}): ${await retry.text()}`); |
| 47 | return retry.json() as Promise<T>; |
| 48 | } |
| 49 | |
| 50 | if (!resp.ok) throw new Error(`API ${method} ${path} failed (${resp.status}): ${await resp.text()}`); |
| 51 | return resp.json() as Promise<T>; |
| 52 | } |
| 53 | |
| 54 | // Auth |
| 55 | // NOTE: login() intentionally bypasses request() to avoid recursive re-login |
no test coverage detected