Initial Post list

This commit is contained in:
2024-07-25 20:55:35 +02:00
parent 9a2673aba2
commit bb1e0eebf5
16 changed files with 327 additions and 96 deletions
+39 -5
View File
@@ -1,3 +1,4 @@
import { PostListAuth, PostListNonAuth } from '../types/Post';
import { User } from '../types/User';
const BASE = 'https://khofmann.userpage.fu-berlin.de/phpCourse/exam/api/';
@@ -5,28 +6,41 @@ const BASE = 'https://khofmann.userpage.fu-berlin.de/phpCourse/exam/api/';
let instance: ApiImpl;
class ApiImpl {
private token: string = '';
//FIXME: PRIVATE when reauth token exists
public token?: string;
constructor() {
if (instance) {
throw new Error('New instance cannot be created!!');
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
//eslint-disable-next-line @typescript-eslint/no-this-alias
instance = this;
}
public logIn = async (email: string, password: string): Promise<User> => {
public hasAuth = () => this.token !== undefined;
//FIXME: Currently returns Auth token, switch to reauth token
public logIn = async (email: string, password: string): Promise<[User, string]> => {
const { user, token } = await (await this.post('login', { email, password })).json();
this.token = token;
return user;
return [user, token];
};
public logOut = async (): Promise<boolean> => {
this.token = undefined;
return await (await this.postAuth('logout')).json();
};
public posts = async (page?: number): Promise<PostListNonAuth | PostListAuth> => {
const url = `posts?p=${page ?? 0}&l=9`;
if (this.token) return await (await this.getAuth(url)).json();
return await (await this.get(url)).json();
};
private post = async (
endpoint: string,
body: Record<string, unknown> | undefined = undefined,
@@ -50,12 +64,32 @@ class ApiImpl {
const response = await fetch(`${BASE}${endpoint}`, {
mode: 'cors',
method: 'post',
headers: { token: this.token, ...headers },
headers: { token: this.token ?? '', ...headers },
body: JSON.stringify(body),
});
if (response.ok) return response;
throw await response.json();
};
private get = async (endpoint: string, headers: HeadersInit | undefined = undefined) => {
const response = await fetch(`${BASE}${endpoint}`, {
mode: 'cors',
method: 'get',
headers,
});
if (response.ok) return response;
throw await response.json();
};
private getAuth = async (endpoint: string, headers: HeadersInit | undefined = undefined) => {
const response = await fetch(`${BASE}${endpoint}`, {
mode: 'cors',
method: 'get',
headers: { token: this.token ?? '', ...headers },
});
if (response.ok) return response;
throw await response.json();
};
}
const Api = new ApiImpl();