This repository has been archived on 2022-05-05. You can view files and clone it, but cannot push or open issues or pull requests.
userausfall/src/api.ts

81 lines
1.9 KiB
TypeScript
Raw Normal View History

import Cookies from "js-cookie";
2021-04-15 16:04:22 +02:00
type HTTPMethod = "GET" | "POST" | "PUT" | "PATCH";
class APIError extends Error {
constructor(message: string, public readonly errors: unknown) {
super(message);
}
}
2021-04-15 16:04:22 +02:00
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);
}
2021-04-15 16:04:22 +02:00
if (authToken != undefined) {
init.headers.set("Authentication", authToken);
}
2021-04-15 16:04:22 +02:00
init.headers.set("Accept", "application/json");
init.headers.set("Content-Type", "application/json");
const response = await fetch(`/api/${endpoint}/`, init);
const dataOrErrors = await response.json();
if (response.status === successStatus) {
return dataOrErrors;
} else {
throw new APIError(response.statusText, dataOrErrors);
2021-04-15 14:24:55 +02:00
}
}
2021-04-15 16:04:22 +02:00
export class User {
2021-04-16 10:36:52 +02:00
email: string | undefined;
password: string | undefined;
2021-04-15 16:04:22 +02:00
private username: string | null = null;
private confidantEmail: string | null = null;
2021-04-16 10:36:52 +02:00
isAuthenticated = false;
2021-04-15 10:05:54 +02:00
private token = "";
2021-04-15 09:31:03 +02:00
static async confirm(uid: string, token: string): Promise<void> {
2021-04-15 16:04:22 +02:00
await request("POST", "users/activation", 204, { uid, token });
2021-04-15 09:31:03 +02:00
}
2021-04-14 11:21:39 +02:00
async login(): Promise<void> {
2021-04-15 16:04:22 +02:00
const response = await request("POST", "token/login", 200, {
2021-04-14 11:21:39 +02:00
email: this.email,
password: this.password,
});
2021-04-15 10:05:54 +02:00
this.token = response.auth_token;
this.isAuthenticated = true;
2021-04-14 11:21:39 +02:00
}
2021-04-15 14:24:55 +02:00
async save(): Promise<void> {
2021-04-15 16:04:22 +02:00
await request(
"PATCH",
"users/me",
200,
{
username: this.username,
},
this.token
);
2021-04-15 14:24:55 +02:00
}
async signup(): Promise<void> {
2021-04-15 16:04:22 +02:00
await request("POST", "users", 201, {
email: this.email,
password: this.password,
});
}
}