login kept in memory

This commit is contained in:
2022-10-21 00:02:00 +02:00
parent ae0eb2c65a
commit 3c5b60e1aa
16 changed files with 160 additions and 57 deletions

View File

@ -0,0 +1,19 @@
export function save(key: string, data: unknown) {
if (data) {
localStorage.setItem(key, JSON.stringify(data));
} else {
remove(key);
}
}
export function remove(key: string) {
localStorage.removeItem(key);
}
export function read<T>(key: string) {
const data = localStorage.getItem(key);
if (data) {
return JSON.parse(data) as T;
}
return null;
}

View File

@ -8,7 +8,10 @@ export async function get<T>(route: string): Promise<T | null> {
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 | null> {
return request<T>('POST', route, data);
}
@ -25,12 +28,13 @@ async function request<T>(
headers: {
'content-type': 'application/json',
},
credentials: process.env.CORS ? 'include' : 'same-origin',
mode: process.env.CORS ? 'cors' : 'same-origin',
method: method,
body: data ? JSON.stringify(data) : null,
});
if (response.ok) {
if (response.ok && response.status !== 204) {
return response.json() as T;
}
return null;

View File

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