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,
item_callback: (item: any) => any successStatus: number,
data: any,
authToken?: string
) { ) {
const init = { const init = {
headers: new Headers(), headers: new Headers(),
method: method, 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);
}
}
static async create(endpoint: string, data: any) {
const init = {
headers: new Headers(),
method: "post",
body: JSON.stringify(data), body: JSON.stringify(data),
}; };
const csrfToken = Cookies.get("csrftoken"); const csrfToken = Cookies.get("csrftoken");
if (csrfToken != undefined) { if (csrfToken != undefined) {
init.headers.set("X-CSRFToken", csrfToken); init.headers.set("X-CSRFToken", csrfToken);
} }
if (authToken != undefined) {
init.headers.set("Authentication", authToken);
}
init.headers.set("Accept", "application/json"); init.headers.set("Accept", "application/json");
init.headers.set("Content-Type", "application/json"); init.headers.set("Content-Type", "application/json");
const response = await fetch(`/api/${endpoint}/`, init); const response = await fetch(`/api/${endpoint}/`, init);
const dataOrErrors = await response.json(); const dataOrErrors = await response.json();
if (response.status === 200) { if (response.status === successStatus) {
return dataOrErrors; return dataOrErrors;
} else { } else {
throw new APIError(response.statusText, dataOrErrors); throw new APIError(response.statusText, dataOrErrors);
} }
} }
protected async put(endpoint: string, token: string, data: any) { export class User {
const init = { private email: string | undefined;
headers: new Headers(), private password: string | undefined;
method: "PATCH", private username: string | null = null;
body: JSON.stringify(data), private confidantEmail: string | null = null;
}; private isAuthenticated = false;
const csrfToken = Cookies.get("csrftoken");
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 {
email: string;
password: string;
username: string | undefined;
confidant_email: string | undefined;
}
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(
"PATCH",
"users/me",
200,
{
username: this.username, 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;