diff --git a/src/util/api.ts b/src/util/api.ts new file mode 100644 index 0000000..43536d3 --- /dev/null +++ b/src/util/api.ts @@ -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 { + const res = await fetch("/api/posts"); + const data = await res.json(); + return data; +} + +export async function getPost(id: string): Promise { + const res = await fetch(`/api/posts/${id}`); + const data = await res.json(); + return data; +} + +export async function createPost(post: NewPost): Promise { + 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 { + 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 { + 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(); +}