FrostByte/client-solid/src/Util/api.ts

76 lines
1.8 KiB
TypeScript
Raw Normal View History

// This file contains types and functions related to interacting with the API.
2023-10-19 02:42:37 +02:00
export interface NewPost {
2023-11-15 07:29:59 +01:00
content: string;
token: string;
2023-10-19 02:42:37 +02:00
}
interface Votes {
2023-11-15 07:29:59 +01:00
up: number;
down: number;
2023-10-19 02:42:37 +02:00
}
export interface Post extends NewPost {
2023-11-15 07:29:59 +01:00
id: string;
createdAt: string;
votes: Votes;
2023-10-19 02:42:37 +02:00
}
2023-11-15 14:21:14 +01:00
// This is what the login and registration responses look like
export interface AuthResponse {
username: string;
token: string;
}
2023-10-19 02:42:37 +02:00
export async function getPosts(): Promise<Post[]> {
const res = await fetch("/api/posts");
2023-10-19 02:42:37 +02:00
const data = await res.json();
return data;
}
export async function getPost(id: string): Promise<Post> {
const res = await fetch(`/api/posts/${id}`);
2023-10-19 02:42:37 +02:00
const data = await res.json();
return data;
}
export async function createPost(post: NewPost): Promise<void> {
await fetch("/api/posts", {
2023-10-19 02:42:37 +02:00
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(post),
});
}
2023-11-15 14:21:14 +01:00
// Send the registration request to the server
export async function submitRegistration(
username: string,
password: string,
captcha: string
): Promise<AuthResponse | undefined> {
const response = await fetch("/api/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password, captcha }),
});
if (response.ok) return await response.json();
}
// Send the login request to the server
export async function submitLogin(
username: string,
password: string
): Promise<AuthResponse | undefined> {
if (username == "" || password == "") return;
const response = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (response.ok) return await response.json();
2023-11-22 15:29:27 +01:00
}