api.ts88 lines, 2.5 KB
| 1 | import { toast } from './toast' |
| 2 | |
| 3 | // What the API answers with. |
| 4 | export type Me = { id: number; handle: string } |
| 5 | export type Post = { |
| 6 | id: number |
| 7 | handle: string |
| 8 | body: string |
| 9 | created_at: string |
| 10 | likes: number |
| 11 | liked: boolean |
| 12 | } |
| 13 | export type Page = { posts: Post[]; next_cursor: number | null } |
| 14 | export type Profile = { |
| 15 | handle: string |
| 16 | joined: string |
| 17 | followers: number |
| 18 | following: number |
| 19 | posts: number |
| 20 | followed_by_me: boolean |
| 21 | } |
| 22 | export type Note = { |
| 23 | id: number |
| 24 | kind: 'like' |
| 25 | actor: string |
| 26 | post_id: number |
| 27 | created_at: string |
| 28 | unread: boolean |
| 29 | body: string // of the post that was liked |
| 30 | } |
| 31 | export type Notes = { |
| 32 | notifications: Note[] |
| 33 | next_cursor: number | null |
| 34 | } |
| 35 | |
| 36 | // The key and whose it is, kept together: the app never has to ask. |
| 37 | type Session = { token: string; handle: string } |
| 38 | const key = 'murmur.session' |
| 39 | export function getSession(): Session | null { |
| 40 | return JSON.parse(localStorage.getItem(key) ?? 'null') |
| 41 | } |
| 42 | export const setSession = (session: Session) => |
| 43 | localStorage.setItem(key, JSON.stringify(session)) |
| 44 | export function signOut() { |
| 45 | localStorage.removeItem(key) |
| 46 | location.assign('/welcome') // a fresh start: no cache, no stream |
| 47 | } |
| 48 | |
| 49 | export class ApiError extends Error { |
| 50 | status: number |
| 51 | constructor(status: number, message: string) { |
| 52 | super(message) |
| 53 | this.status = status |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | export const sleep = (ms: number) => |
| 58 | new Promise((resolve) => setTimeout(resolve, ms)) |
| 59 | |
| 60 | // request calls the API under /api, the app's own address, with the |
| 61 | // token. It turns {"error": "…"} into an ApiError. |
| 62 | export async function request<T>( |
| 63 | path: string, |
| 64 | { json, ...init }: RequestInit & { json?: unknown } = {}, |
| 65 | waits = 2, |
| 66 | ): Promise<T> { |
| 67 | const headers = new Headers(init.headers) |
| 68 | const token = getSession()?.token |
| 69 | if (token) headers.set('Authorization', `Bearer ${token}`) |
| 70 | if (json !== undefined) { |
| 71 | headers.set('Content-Type', 'application/json') |
| 72 | init.body = JSON.stringify(json) |
| 73 | } |
| 74 | const res = await fetch(`/api${path}`, { ...init, headers }) |
| 75 | if (res.status === 429 && waits > 0) { |
| 76 | // Out of tokens: wait as long as the server says, then go again. |
| 77 | // Twice at most; after that the screen says so. |
| 78 | const wait = Number(res.headers.get('Retry-After')) || 1 |
| 79 | toast(`Busy moment. Trying again in ${wait}s.`) |
| 80 | await sleep(wait * 1000) |
| 81 | return request(path, { json, ...init }, waits - 1) |
| 82 | } |
| 83 | if (!res.ok) { |
| 84 | const { error } = await res.json().catch(() => ({})) |
| 85 | throw new ApiError(res.status, error ?? res.statusText) |
| 86 | } |
| 87 | return res.status === 204 ? (undefined as T) : res.json() |
| 88 | } |