API boilerplate gluecode

This commit is contained in:
Imbus 2023-12-14 16:47:34 +01:00
parent c5fa0ac6f9
commit d7f4f11ced

76
src/util/api.ts Normal file
View file

@ -0,0 +1,76 @@
// This file contains types and functions related to interacting with the API.
const URL = "https://shitpost.se";
export interface NewPost {
content: string;
token: string;
}
interface Votes {
up: number;
down: number;
}
export interface Post extends NewPost {
id: string;
createdAt: string;
votes: Votes;
}
// This is what the login and registration responses look like
export interface AuthResponse {
username: string;
token: string;
}
export async function getPosts(): Promise<Post[]> {
const res = await fetch("/api/posts");
const data = await res.json();
return data;
}
export async function getPost(id: string): Promise<Post> {
const res = await fetch(`/api/posts/${id}`);
const data = await res.json();
return data;
}
export async function createPost(post: NewPost): Promise<void> {
await fetch("/api/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(post),
});
}
// 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();
}