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

69 lines
1.9 KiB
TypeScript

import Cookies from "js-cookie";
class APIError extends Error {
constructor(message: string, public readonly errors: unknown) {
super(message);
}
}
class Model {
static async fetch(
method: "get" | "post",
endpoint: string,
item_callback: (item: any) => any
) {
const init = {
headers: new Headers(),
method: method,
//body: JSON.stringify({})
};
const csrfToken = Cookies.get("csrftoken");
if (csrfToken != undefined) {
init.headers.set("X-CSRFToken", csrfToken);
}
init.headers.set("Accept", "application/json");
init.headers.set("Content-Type", "application/json");
const response = await fetch(`/api/${endpoint}`, init);
const dataOrErrors: Array<any> = await response.json();
if (response.status === 200) {
return dataOrErrors.map(item_callback);
} else {
throw new APIError(response.statusText, dataOrErrors);
}
}
protected async create(endpoint: string, data: any) {
const init = {
headers: new Headers(),
method: "post",
body: JSON.stringify(data),
};
const csrfToken = Cookies.get("csrftoken");
if (csrfToken != undefined) {
init.headers.set("X-CSRFToken", csrfToken);
}
init.headers.set("Accept", "application/json");
init.headers.set("Content-Type", "application/json");
const response = await fetch(`/api/${endpoint}/`, init);
const dataOrErrors: Array<any> = await response.json();
if (response.status !== 201) {
throw new APIError(response.statusText, dataOrErrors);
}
}
}
interface UserData {
email: string;
password: string;
}
export class User extends Model implements UserData {
constructor(public email: string, public password: string) {
super();
}
async signup(): Promise<void> {
await super.create("users", { email: this.email, password: this.password });
}
}