better errors

This commit is contained in:
2022-10-26 00:16:41 +02:00
parent 78addafe18
commit 0f53063832
6 changed files with 42 additions and 25 deletions

View File

@ -4,18 +4,15 @@ enum Methods {
'PUT' = 'PUT',
}
export async function get<T>(route: string): Promise<T | null> {
export async function get<T>(route: string): Promise<T> {
return request<T>('GET', route);
}
export async function post<T>(
route: string,
data?: unknown,
): Promise<T | null> {
export async function post<T>(route: string, data?: unknown): Promise<T> {
return request<T>('POST', route, data);
}
export async function put<T>(route: string, data: unknown): Promise<T | null> {
export async function put<T>(route: string, data: unknown): Promise<T> {
return request<T>('PUT', route, data);
}
@ -23,7 +20,7 @@ async function request<T>(
method: keyof typeof Methods,
route: string,
data?: unknown,
): Promise<T | null> {
): Promise<T> {
const response = await fetch(`${process.env.APIURL}${route}`, {
headers: {
'content-type': 'application/json',
@ -34,8 +31,11 @@ async function request<T>(
body: data ? JSON.stringify(data) : null,
});
if (!response.ok) throw new Error(await response.json());
if (response.ok && response.status !== 204) {
return response.json() as T;
}
return null;
return {} as T;
}

View File

@ -1,22 +1,18 @@
import type { CreateUserBody, LoginUserBody, UserInfo } from '@core';
import { post, get } from './request';
import { currentUser } from '../store/user';
export async function login(raw: LoginUserBody) {
const user = await post<UserInfo>('/user/login', raw);
currentUser.set(user);
return user;
return post<UserInfo>('/user/login', raw);
}
export async function logout() {
await post('/user/logout');
currentUser.set(null);
await post<void>('/user/logout');
}
export async function read(uuid: string) {
const user = await get<UserInfo>(`/user/read/${uuid}`);
return get<UserInfo>(`/user/read/${uuid}`);
}
export async function create(raw: CreateUserBody) {
const user = await post<UserInfo>('/user/create', raw);
return post<UserInfo>('/user/create', raw);
}