Delete Post

This commit is contained in:
2024-07-26 20:56:32 +02:00
parent 0929371c10
commit a515c447e0
14 changed files with 180 additions and 56 deletions
+21 -14
View File
@@ -1,4 +1,4 @@
import { PostListAuth, PostListNonAuth } from '../types/Post';
import { PostAuth, PostListAuth, PostListNonAuth } from '../types/Post';
import { User } from '../types/User';
const BASE = 'https://khofmann.userpage.fu-berlin.de/phpCourse/exam/api/';
@@ -27,7 +27,6 @@ class ApiImpl {
public logIn = async (email: string, password: string): Promise<void> => {
const { user, token } = await (await this.post('login', { email, password })).json();
this.self = user;
this.isAdmin = user.isAdmin;
this.token = token;
};
@@ -50,15 +49,17 @@ class ApiImpl {
return await (await this.get(url)).json();
};
public deletePost = async (id: number): Promise<PostAuth> => {
return await (await this.delete(`posts/${id}`)).json();
};
public user = async (id?: number): Promise<User> => {
return await (await this.getAuth(`users/${id ?? this.self?.id}`)).json();
};
private post = async (
endpoint: string,
body: Record<string, unknown> | undefined = undefined,
headers: HeadersInit | undefined = undefined
) => {
/* Internal */
private post = async (endpoint: string, body?: Record<string, unknown>, headers?: HeadersInit) => {
const response = await fetch(`${BASE}${endpoint}`, {
mode: 'cors',
method: 'post',
@@ -69,11 +70,7 @@ class ApiImpl {
throw await response.json();
};
private postAuth = async (
endpoint: string,
body: Record<string, unknown> | undefined = undefined,
headers: HeadersInit | undefined = undefined
) => {
private postAuth = async (endpoint: string, body?: Record<string, unknown>, headers?: HeadersInit) => {
const response = await fetch(`${BASE}${endpoint}`, {
mode: 'cors',
method: 'post',
@@ -84,7 +81,7 @@ class ApiImpl {
throw await response.json();
};
private get = async (endpoint: string, headers: HeadersInit | undefined = undefined) => {
private get = async (endpoint: string, headers?: HeadersInit) => {
const response = await fetch(`${BASE}${endpoint}`, {
mode: 'cors',
method: 'get',
@@ -94,7 +91,7 @@ class ApiImpl {
throw await response.json();
};
private getAuth = async (endpoint: string, headers: HeadersInit | undefined = undefined) => {
private getAuth = async (endpoint: string, headers?: HeadersInit) => {
const response = await fetch(`${BASE}${endpoint}`, {
mode: 'cors',
method: 'get',
@@ -103,6 +100,16 @@ class ApiImpl {
if (response.ok) return response;
throw await response.json();
};
private delete = async (endpoint: string, headers?: HeadersInit) => {
const response = await fetch(`${BASE}${endpoint}`, {
mode: 'cors',
method: 'delete',
headers: { token: this.token ?? '', ...headers },
});
if (response.ok) return response;
throw await response.json();
};
}
const Api = new ApiImpl();