Refactor api functions

This commit is contained in:
aldrin 2021-04-15 16:04:22 +02:00
parent 1afea69854
commit 87d72be3fa
2 changed files with 49 additions and 90 deletions

View file

@ -1,107 +1,57 @@
import Cookies from "js-cookie"; import Cookies from "js-cookie";
type HTTPMethod = "GET" | "POST" | "PUT" | "PATCH";
class APIError extends Error { class APIError extends Error {
constructor(message: string, public readonly errors: unknown) { constructor(message: string, public readonly errors: unknown) {
super(message); super(message);
} }
} }
class Model { async function request(
static async fetch( method: HTTPMethod,
method: "get" | "post", endpoint: string,
endpoint: string, successStatus: number,
item_callback: (item: any) => any data: any,
) { authToken?: string
const init = { ) {
headers: new Headers(), const init = {
method: method, headers: new Headers(),
//body: JSON.stringify({}) method: method,
}; body: JSON.stringify(data),
const csrfToken = Cookies.get("csrftoken"); };
if (csrfToken != undefined) { const csrfToken = Cookies.get("csrftoken");
init.headers.set("X-CSRFToken", 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);
}
} }
if (authToken != undefined) {
static async create(endpoint: string, data: any) { init.headers.set("Authentication", authToken);
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 = await response.json();
if (response.status === 200) {
return dataOrErrors;
} else {
throw new APIError(response.statusText, dataOrErrors);
}
} }
init.headers.set("Accept", "application/json");
protected async put(endpoint: string, token: string, data: any) { init.headers.set("Content-Type", "application/json");
const init = { const response = await fetch(`/api/${endpoint}/`, init);
headers: new Headers(), const dataOrErrors = await response.json();
method: "PATCH", if (response.status === successStatus) {
body: JSON.stringify(data), return dataOrErrors;
}; } else {
const csrfToken = Cookies.get("csrftoken"); throw new APIError(response.statusText, dataOrErrors);
if (csrfToken != undefined) {
init.headers.set("X-CSRFToken", csrfToken);
}
init.headers.set("Authorization", `Token ${token}`);
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 === 200) {
return dataOrErrors;
} else {
throw new APIError(response.statusText, dataOrErrors);
}
} }
} }
interface UserData { export class User {
email: string; private email: string | undefined;
password: string; private password: string | undefined;
username: string | undefined; private username: string | null = null;
confidant_email: string | undefined; private confidantEmail: string | null = null;
} private isAuthenticated = false;
export class User extends Model implements UserData {
public isAuthenticated = false;
private token = ""; private token = "";
constructor(
public email: string,
public password: string,
public username: string | undefined,
public confidant_email: string | undefined
) {
super();
}
static async confirm(uid: string, token: string): Promise<void> { static async confirm(uid: string, token: string): Promise<void> {
await super.create("users/activation", { uid, token }); await request("POST", "users/activation", 204, { uid, token });
} }
async login(): Promise<void> { async login(): Promise<void> {
const response = await Model.create("token/login", { const response = await request("POST", "token/login", 200, {
email: this.email, email: this.email,
password: this.password, password: this.password,
}); });
@ -110,12 +60,21 @@ export class User extends Model implements UserData {
} }
async save(): Promise<void> { async save(): Promise<void> {
await super.put("users/me", this.token, { await request(
username: this.username, "PATCH",
}); "users/me",
200,
{
username: this.username,
},
this.token
);
} }
async signup(): Promise<void> { async signup(): Promise<void> {
await Model.create("users", { email: this.email, password: this.password }); await request("POST", "users", 201, {
email: this.email,
password: this.password,
});
} }
} }

View file

@ -26,7 +26,7 @@ import UserTable from "@/components/UserTable.vue";
@Component({ components: { UserTable, LoginForm } }) @Component({ components: { UserTable, LoginForm } })
export default class Home extends Vue { export default class Home extends Vue {
private isConfirmation = false; private isConfirmation = false;
private user = new User("", "", undefined, undefined); private user = new User();
private async created() { private async created() {
if (this.$route.name === "Confirm") this.isConfirmation = true; if (this.$route.name === "Confirm") this.isConfirmation = true;