import Cookies from "js-cookie"; type HTTPMethod = "GET" | "POST" | "PUT" | "PATCH"; class APIError extends Error { constructor(message: string, public readonly errors: unknown) { super(message); } } async function request( method: HTTPMethod, endpoint: string, successStatus: number, data: any, authToken?: string ) { const init = { headers: new Headers(), method: method, body: JSON.stringify(data), }; const csrfToken = Cookies.get("csrftoken"); if (csrfToken != undefined) { init.headers.set("X-CSRFToken", csrfToken); } if (authToken != undefined) { init.headers.set("Authentication", authToken); } init.headers.set("Accept", "application/json"); init.headers.set("Content-Type", "application/json"); const response = await fetch(`/api/${endpoint}/`, init); if (response.status !== 204) { if (response.status === successStatus) { return await response.json(); } else { throw new APIError(response.statusText, await response.json()); } } } export class User { email: string | undefined; password: string | undefined; private username: string | null = null; private confidantEmail: string | null = null; isAuthenticated = false; private token = ""; static async confirm(uid: string, token: string): Promise { await request("POST", "users/activation", 204, { uid, token }); } async login(): Promise { const response = await request("POST", "token/login", 200, { email: this.email, password: this.password, }); this.token = response.auth_token; this.isAuthenticated = true; } async save(): Promise { await request( "PATCH", "users/me", 200, { username: this.username, }, this.token ); } async signup(): Promise { await request("POST", "users", 201, { email: this.email, password: this.password, }); } }