API boilerplate gluecode
This commit is contained in:
parent
c5fa0ac6f9
commit
d7f4f11ced
1 changed files with 76 additions and 0 deletions
76
src/util/api.ts
Normal file
76
src/util/api.ts
Normal 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();
|
||||||
|
}
|
Loading…
Reference in a new issue