Refactor api requests

This commit is contained in:
MarkasAis 2025-02-09 02:39:02 +02:00
parent a5c8ba0e34
commit 47c13bdfbc
33 changed files with 560 additions and 862 deletions

View file

@ -14,6 +14,8 @@ import { UserType } from "@/types/UserType";
import { useRouter } from 'next/navigation';
import { GameType } from "@/types/GameType";
import { PlatformType, DownloadLinkType } from "@/types/DownloadLinkType";
import { getSelf, searchUsers } from "@/requests/user";
import { getCurrentGame, postGame, updateGame } from "@/requests/game";
@ -61,15 +63,7 @@ export default function CreateGamePage() {
const handleAuthorSearch = async (query: string) => {
if (query.length < 3) return;
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/user/search?q=${query}`
: `http://localhost:3005/api/v1/user/search?q=${query}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const response = await searchUsers(query);
if (response.ok) {
const data = await response.json();
@ -90,24 +84,12 @@ export default function CreateGamePage() {
setMounted(true);
const load = async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const response = await getSelf();
const localuser = await response.json();
setUser(localuser);
/*
const tagResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/tags`
: `http://localhost:3005/api/v1/tags`
);
const tagResponse = await getTags();
if (tagResponse.ok) {
const newoptions: {
@ -155,15 +137,7 @@ export default function CreateGamePage() {
useEffect(() => {
const checkExistingGame = async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self/current-game?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self/current-game?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const response = await getCurrentGame()
console.log("say");
if (response.ok) {
const gameData = await response.json();
@ -249,34 +223,18 @@ export default function CreateGamePage() {
setWaitingPost(true);
try {
const requestMethod = editGame ? "PUT" : "POST";
const endpoint = editGame ? `/games/${prevSlug}` : "/games/create";
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1${endpoint}`
: `http://localhost:3005/api/v1${endpoint}`,
{
body: JSON.stringify({
name: title,
slug: gameSlug,
description: sanitizedHtml,
thumbnail: thumbnailUrl,
downloadLinks: downloadLinks.map((link) => ({
const links = downloadLinks.map((link) => ({
url: link.url,
platform: link.platform,
})),
userSlug,
contributors: selectedAuthors.map((author) => author.id),
}),
method: requestMethod,
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
}));
const contributors = selectedAuthors.map((author) => author.id);
const request = editGame ?
updateGame(prevSlug, title, gameSlug, sanitizedHtml, thumbnailUrl, links, userSlug, contributors) :
postGame(title, gameSlug, sanitizedHtml, thumbnailUrl, links, userSlug, contributors);
const response = await request;
if (response.status === 401) {
setErrors({ content: "Invalid user" });

View file

@ -20,6 +20,9 @@ import { useTheme } from "next-themes";
import Timers from "@/components/timers";
import Streams from "@/components/streams";
import { UserType } from "@/types/UserType";
import { getSelf } from "@/requests/user";
import { getTags } from "@/requests/tag";
import { postPost } from "@/requests/post";
export default function CreatePostPage() {
const [title, setTitle] = useState("");
@ -49,24 +52,12 @@ export default function CreatePostPage() {
setMounted(true);
const load = async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const response = await getSelf();
const localuser = await response.json();
setUser(localuser);
const tagResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/tags`
: `http://localhost:3005/api/v1/tags`
);
const tagResponse = await getTags();
if (tagResponse.ok) {
const newoptions: {
@ -226,31 +217,13 @@ export default function CreatePostPage() {
}
}
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post"
: "http://localhost:3005/api/v1/post",
{
body: JSON.stringify({
title: title,
content: sanitizedHtml,
sticky,
username: getCookie("user"),
tags: [
const combinedTags = [
...tags,
...(options
? options.filter((tag) => tag.isFixed).map((tag) => tag.id)
: []),
],
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
];
const response = await postPost(title, sanitizedHtml, sticky, combinedTags);
if (response.status == 401) {
setErrors({ content: "Invalid user" });

View file

@ -9,6 +9,8 @@ import { useRouter } from 'next/navigation';
import { GameType } from '@/types/GameType';
import { UserType } from '@/types/UserType';
import { DownloadLinkType } from '@/types/DownloadLinkType';
import { getGame } from '@/requests/game';
import { getSelf } from '@/requests/user';
export default function GamePage({ params }: { params: Promise<{ gameSlug: string }> }) {
const resolvedParams = use(params);
@ -20,15 +22,7 @@ export default function GamePage({ params }: { params: Promise<{ gameSlug: strin
useEffect(() => {
const fetchGameAndUser = async () => {
// Fetch the game data
const gameResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/games/${gameSlug}`
: `http://localhost:3005/api/v1/games/${gameSlug}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const gameResponse = await getGame(gameSlug);
if (gameResponse.ok) {
const gameData = await gameResponse.json();
@ -47,15 +41,7 @@ export default function GamePage({ params }: { params: Promise<{ gameSlug: strin
// Fetch the logged-in user data
if (getCookie("token")) {
const userResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const userResponse = await getSelf();
if (userResponse.ok) {
const userData = await userResponse.json();

View file

@ -1,5 +1,6 @@
"use client";
import { login } from "@/requests/auth";
import { Button, Form, Input, Link } from "@nextui-org/react";
import { redirect } from "next/navigation";
import { useState } from "react";
@ -40,17 +41,7 @@ export default function UserPage() {
return;
}
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/login"
: "http://localhost:3005/api/v1/login",
{
body: JSON.stringify({ username: username, password: password }),
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
}
);
const response = await login(username, password);
if (response.status == 401) {
setErrors({ password: "Invalid username or password" });

View file

@ -3,16 +3,12 @@
import { redirect } from "next/navigation";
import React, { useEffect } from "react";
import { toast } from "react-toastify";
import { logout as logoutUser } from "@/requests/auth";
export default function UserPage() {
useEffect(() => {
async function logout() {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/logout"
: "http://localhost:3005/api/v1/logout",
{ method: "POST", credentials: "include" }
);
const response = await logoutUser();
if (response.ok) {
document.cookie =

View file

@ -39,6 +39,10 @@ import { toast } from "react-toastify";
import Editor from "@/components/editor";
import sanitizeHtml from "sanitize-html";
import CommentCard from "@/components/posts/CommentCard";
import { getSelf } from "@/requests/user";
import { deletePost, getPost, stickPost } from "@/requests/post";
import { assignAdmin, assignMod } from "@/requests/mod";
import { postComment } from "@/requests/comment";
export default function PostPage() {
const [post, setPost] = useState<PostType>();
@ -68,38 +72,14 @@ export default function PostPage() {
setLoading(true);
// Fetch the user
const userResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
if (userResponse.ok) {
const userData = await userResponse.json();
const userResponse = await getSelf();
const userData = userResponse.ok ? await userResponse.json() : undefined;
setUser(userData);
const postResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/post?slug=${slug}&user=${userData.slug}`
: `http://localhost:3005/api/v1/post?slug=${slug}&user=${userData.slug}`
);
const postResponse = await getPost(`${slug}`, userData?.slug);
setPost(await postResponse.json());
setLoading(false);
} else {
setUser(undefined);
const postResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/post?slug=${slug}`
: `http://localhost:3005/api/v1/post?slug=${slug}`
);
setPost(await postResponse.json());
setLoading(false);
}
};
loadUserAndPosts();
@ -235,25 +215,7 @@ export default function PostPage() {
startContent={<Trash />}
description="Delete your post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post"
: "http://localhost:3005/api/v1/post",
{
body: JSON.stringify({
postId: post.id,
username: getCookie("user"),
}),
method: "DELETE",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await deletePost(post.id);
if (response.ok) {
toast.success("Deleted post");
@ -276,25 +238,7 @@ export default function PostPage() {
startContent={<X />}
description="Remove this post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post"
: "http://localhost:3005/api/v1/post",
{
body: JSON.stringify({
postId: post.id,
username: getCookie("user"),
}),
method: "DELETE",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await deletePost(post.id);
if (response.ok) {
toast.success("Removed post");
@ -312,26 +256,7 @@ export default function PostPage() {
startContent={<StarOff />}
description="Unsticky post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post/sticky"
: "http://localhost:3005/api/v1/post/sticky",
{
body: JSON.stringify({
postId: post.id,
sticky: false,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await stickPost(post.id, false);
if (response.ok) {
toast.success("Unsticked post");
@ -349,26 +274,7 @@ export default function PostPage() {
startContent={<Star />}
description="Sticky post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post/sticky"
: "http://localhost:3005/api/v1/post/sticky",
{
body: JSON.stringify({
postId: post.id,
sticky: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await stickPost(post.id, true);
if (response.ok) {
toast.success("Unsticked post");
@ -387,26 +293,7 @@ export default function PostPage() {
startContent={<Shield />}
description="Promote user to Mod"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/mod"
: "http://localhost:3005/api/v1/mod",
{
body: JSON.stringify({
targetname: post.author.slug,
mod: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await assignMod(post.author.slug, true);
if (response.ok) {
toast.success("Promoted User to Mod");
@ -431,25 +318,7 @@ export default function PostPage() {
startContent={<ShieldX />}
description="Demote user from Mod"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/mod"
: "http://localhost:3005/api/v1/mod",
{
body: JSON.stringify({
targetname: post.author.slug,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await assignMod(post.author.slug, false);
if (response.ok) {
toast.success("Demoted User");
@ -470,26 +339,7 @@ export default function PostPage() {
startContent={<ShieldAlert />}
description="Promote user to Admin"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/mod"
: "http://localhost:3005/api/v1/mod",
{
body: JSON.stringify({
targetname: post.author.slug,
admin: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await assignAdmin(post.author.slug, true);
if (response.ok) {
toast.success("Promoted User to Admin");
@ -514,26 +364,7 @@ export default function PostPage() {
startContent={<ShieldX />}
description="Demote user to mod"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/mod"
: "http://localhost:3005/api/v1/mod",
{
body: JSON.stringify({
targetname: post.author.slug,
mod: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await assignAdmin(post.author.slug, false);
if (response.ok) {
toast.success("Demoted User to Mod");
@ -582,24 +413,7 @@ export default function PostPage() {
const sanitizedHtml = sanitizeHtml(content);
setWaitingPost(true);
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/comment"
: "http://localhost:3005/api/v1/comment",
{
body: JSON.stringify({
content: sanitizedHtml,
username: getCookie("user"),
postId: post?.id,
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
const response = await postComment(sanitizedHtml, post!.id);
if (response.status == 401) {
toast.error("Invalid User");

View file

@ -10,6 +10,7 @@ import { useEffect, useState } from "react";
import { toast } from "react-toastify";
import { LoaderCircle } from "lucide-react";
import Image from "next/image";
import { getSelf, updateUser } from "@/requests/user";
export default function UserPage() {
const [user, setUser] = useState<UserType>();
@ -30,15 +31,7 @@ export default function UserPage() {
return;
}
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const response = await getSelf();
if (response.status == 200) {
const data = await response.json();
@ -80,25 +73,7 @@ export default function UserPage() {
setWaitingSave(true);
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/user"
: "http://localhost:3005/api/v1/user",
{
body: JSON.stringify({
slug: user.slug,
name: name,
bio: sanitizedBio,
profilePicture: profilePicture,
bannerPicture: bannerPicture,
}),
method: "PUT",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
}
);
const response = await updateUser(user.slug, name, sanitizedBio, profilePicture, bannerPicture);
if (response.ok) {
toast.success("Changed settings");

View file

@ -1,5 +1,6 @@
"use client";
import { signup } from "@/requests/auth";
import { Button, Form, Input, Link } from "@nextui-org/react";
import { redirect } from "next/navigation";
import { useState } from "react";
@ -66,17 +67,7 @@ export default function UserPage() {
return;
}
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/signup"
: "http://localhost:3005/api/v1/signup",
{
body: JSON.stringify({ username: username, password: password }),
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
}
);
const response = await signup(username, password);
if (response.status == 409) {
setErrors({ username: "User already exists" });

View file

@ -1,5 +1,6 @@
"use client";
import { getUser } from "@/requests/user";
import { UserType } from "@/types/UserType";
import { Avatar } from "@nextui-org/react";
import Image from "next/image";
@ -12,11 +13,7 @@ export default function UserPage() {
useEffect(() => {
const fetchUser = async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/user?slug=${slug}`
: `http://localhost:3005/api/v1/user?slug=${slug}`
);
const response = await getUser(`${slug}`);
setUser(await response.json());
};

View file

@ -3,6 +3,7 @@
import { Calendar } from "lucide-react";
import { useEffect, useState } from "react";
import { getCurrentJam, ActiveJamResponse } from "../../helpers/jam";
import { getTopThemes } from "@/requests/theme";
export default function JamHeader() {
const [activeJamResponse, setActiveJamResponse] =
@ -18,11 +19,7 @@ export default function JamHeader() {
// If we're in Jamming phase, fetch top themes and pick the first one
if ((jamData?.phase === "Jamming" || jamData?.phase === "Rating") && jamData.jam) {
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/top-themes"
: "http://localhost:3005/api/v1/themes/top-themes"
);
const response = await getTopThemes();
if (response.ok) {
const themes = await response.json();

View file

@ -18,6 +18,7 @@ import { JamType } from "@/types/JamType";
import { UserType } from "@/types/UserType";
import MobileNavbarUser from "./MobileNavbarUser";
import ThemeToggle from "../theme-toggle";
import { getSelf } from "@/requests/user";
export default function MobileNavbar() {
@ -39,19 +40,9 @@ export default function MobileNavbar() {
return;
}
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const response = await getSelf();
const user = await response.json();
if (
currentJam &&
user.jams.filter((jam: JamType) => jam.id == currentJam.id).length > 0

View file

@ -33,6 +33,8 @@ import NavbarButtonAction from "./NavbarButtonAction";
import { toast } from "react-toastify";
import NavbarIconLink from "./NavbarIconLink";
import ThemeToggle from "../theme-toggle";
import { getSelf } from "@/requests/user";
import { getCurrentGame } from "@/requests/game";
export default function PCNavbar() {
const pathname = usePathname();
@ -68,28 +70,12 @@ export default function PCNavbar() {
return;
}
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const response = await getSelf();
const user = await response.json();
// Check if user has a game in current jam
const gameResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self/current-game?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self/current-game?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const gameResponse = await getCurrentGame();
if (gameResponse.ok) {
const gameData = await gameResponse.json();

View file

@ -9,6 +9,7 @@ import { toast } from "react-toastify";
import { getCookie, hasCookie } from "@/helpers/cookie";
import sanitizeHtml from "sanitize-html";
import LikeButton from "./LikeButton";
import { postComment } from "@/requests/comment";
export default function CommentCard({ comment }: { comment: CommentType }) {
const [creatingReply, setCreatingReply] = useState<boolean>(false);
@ -93,24 +94,7 @@ export default function CommentCard({ comment }: { comment: CommentType }) {
const sanitizedHtml = sanitizeHtml(content);
setWaitingPost(true);
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/comment"
: "http://localhost:3005/api/v1/comment",
{
body: JSON.stringify({
content: sanitizedHtml,
username: getCookie("user"),
commentId: comment?.id,
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
const response = await postComment(sanitizedHtml, comment!.id);
if (response.status == 401) {
toast.error("Invalid User");

View file

@ -7,6 +7,8 @@ import { getCookie } from "@/helpers/cookie";
import { redirect } from "next/navigation";
import { useState, useEffect } from "react";
import { useTheme } from "next-themes";
import { postComment } from "@/requests/comment";
import { postLike } from "@/requests/like";
export default function LikeButton({
likes,
@ -56,24 +58,7 @@ export default function LikeButton({
redirect("/login");
}
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/like"
: "http://localhost:3005/api/v1/like",
{
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
body: JSON.stringify({
username: getCookie("user"),
postId: !isComment ? parentId : 0,
commentId: isComment ? parentId : 0,
}),
}
);
const response = await postLike(parentId, isComment);
if (!updatedLiked) {
setLikeEffect(true);

View file

@ -37,6 +37,8 @@ import { useEffect, useState } from "react";
import { getCookie } from "@/helpers/cookie";
import { toast } from "react-toastify";
import { TagType } from "@/types/TagType";
import { deletePost, stickPost } from "@/requests/post";
import { assignAdmin, assignMod } from "@/requests/mod";
export default function PostCard({
post,
@ -231,23 +233,7 @@ export default function PostCard({
startContent={<Trash />}
description="Delete your post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post"
: "http://localhost:3005/api/v1/post",
{
body: JSON.stringify({
postId: post.id,
username: getCookie("user"),
}),
method: "DELETE",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
const response = await deletePost(post.id);
if (response.ok) {
toast.success("Deleted post");
@ -270,23 +256,7 @@ export default function PostCard({
startContent={<X />}
description="Remove this post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post"
: "http://localhost:3005/api/v1/post",
{
body: JSON.stringify({
postId: post.id,
username: getCookie("user"),
}),
method: "DELETE",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
const response = await deletePost(post.id);
if (response.ok) {
toast.success("Removed post");
@ -304,26 +274,7 @@ export default function PostCard({
startContent={<StarOff />}
description="Unsticky post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post/sticky"
: "http://localhost:3005/api/v1/post/sticky",
{
body: JSON.stringify({
postId: post.id,
sticky: false,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await stickPost(post.id, false);
if (response.ok) {
toast.success("Unsticked post");
@ -341,26 +292,7 @@ export default function PostCard({
startContent={<Star />}
description="Sticky post"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/post/sticky"
: "http://localhost:3005/api/v1/post/sticky",
{
body: JSON.stringify({
postId: post.id,
sticky: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await stickPost(post.id, true);
if (response.ok) {
toast.success("Stickied post");
@ -379,26 +311,7 @@ export default function PostCard({
startContent={<Shield />}
description="Promote user to Mod"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/mod"
: "http://localhost:3005/api/v1/mod",
{
body: JSON.stringify({
targetname: post.author.slug,
mod: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await assignMod(post.author.slug, true);
if (response.ok) {
toast.success("Promoted User to Mod");
@ -423,25 +336,7 @@ export default function PostCard({
startContent={<ShieldX />}
description="Demote user from Mod"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/mod"
: "http://localhost:3005/api/v1/mod",
{
body: JSON.stringify({
targetname: post.author.slug,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await assignMod(post.author.slug, false);
if (response.ok) {
toast.success("Demoted User");
@ -462,26 +357,7 @@ export default function PostCard({
startContent={<ShieldAlert />}
description="Promote user to Admin"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/mod"
: "http://localhost:3005/api/v1/mod",
{
body: JSON.stringify({
targetname: post.author.slug,
admin: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await assignAdmin(post.author.slug, true);
if (response.ok) {
toast.success("Promoted User to Admin");
@ -506,26 +382,7 @@ export default function PostCard({
startContent={<ShieldX />}
description="Demote user to mod"
onPress={async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/mod"
: "http://localhost:3005/api/v1/mod",
{
body: JSON.stringify({
targetname: post.author.slug,
mod: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
const response = await assignAdmin(post.author.slug, false);
if (response.ok) {
toast.success("Demoted User to Mod");

View file

@ -43,6 +43,9 @@ import { PostTime } from "@/types/PostTimes";
import { TagType } from "@/types/TagType";
import { useTheme } from "next-themes";
import StickyPostCard from "./StickyPostCard";
import { getTags } from "@/requests/tag";
import { getSelf } from "@/requests/user";
import { getPosts } from "@/requests/post";
export default function Posts() {
const [posts, setPosts] = useState<PostType[]>();
@ -77,11 +80,7 @@ export default function Posts() {
const loadUserAndPosts = async () => {
setLoading(true);
const tagResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/tags`
: `http://localhost:3005/api/v1/tags`
);
const tagResponse = await getTags();
if (tagResponse.ok) {
const tagObject: {
@ -109,113 +108,19 @@ export default function Posts() {
}
// Fetch the user
const userResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/self?username=${getCookie("user")}`
: `http://localhost:3005/api/v1/self?username=${getCookie("user")}`,
{
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
if (userResponse.ok) {
const userData = await userResponse.json();
const userResponse = await getSelf();
const userData = userResponse.ok ? await userResponse.json() : undefined;
setUser(userData);
// Fetch posts with userSlug if user is available
const postsResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/posts?sort=${sort}&user=${
userData.slug
}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}`
: `http://localhost:3005/api/v1/posts?sort=${sort}&user=${
userData.slug
}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}`
);
// Fetch posts (with userSlug if user is available)
const postsResponse = await getPosts(sort, time, false, tagRules, userData?.slug);
setPosts(await postsResponse.json());
// Sticky posts
// Fetch posts with userSlug if user is available
const stickyPostsResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/posts?sort=${sort}&user=${
userData.slug
}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}&sticky=true`
: `http://localhost:3005/api/v1/posts?sort=${sort}&user=${
userData.slug
}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}&sticky=true`
);
// Fetch posts (with userSlug if user is available)
const stickyPostsResponse = await getPosts(sort, time, true, tagRules, userData?.slug);
setStickyPosts(await stickyPostsResponse.json());
setLoading(false);
} else {
setUser(undefined);
// Fetch posts without userSlug if user is not available
const postsResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/posts?sort=${sort}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}`
: `http://localhost:3005/api/v1/posts?sort=${sort}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}`
);
setPosts(await postsResponse.json());
// Fetch posts without userSlug if user is not available
const stickyPostsResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/posts?sort=${sort}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}&sticky=true`
: `http://localhost:3005/api/v1/posts?sort=${sort}&time=${time}&tags=${
tagRules
? Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
: ""
}&sticky=true`
);
setStickyPosts(await stickyPostsResponse.json());
setLoading(false);
}
};
loadUserAndPosts();

View file

@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
import { FeaturedStreamerType } from "@/types/FeaturedStreamerType";
import { Image } from "@nextui-org/react";
import NextImage from "next/image";
import { getStreamers } from "@/requests/streamer";
export default function Streams() {
const [streamers, setStreamers] = useState<FeaturedStreamerType[]>([]);
@ -12,11 +13,7 @@ export default function Streams() {
useEffect(() => {
const fetchStreamers = async () => {
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/streamers/get"
: "http://localhost:3005/api/v1/streamers/get"
);
const response = await getStreamers();
if (!response.ok) {
throw new Error("Failed to fetch featured streamers");
}

View file

@ -9,6 +9,7 @@ import {
joinJam
} from "@/helpers/jam";
import {ThemeType} from "@/types/ThemeType";
import { getRandomThemes, getSlaughterThemes, postThemeSlaughterVote } from "@/requests/theme";
export default function ThemeSlaughter() {
const [randomTheme, setRandomTheme] = useState<ThemeType | null>(null);
@ -61,15 +62,7 @@ export default function ThemeSlaughter() {
}
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/random"
: "http://localhost:3005/api/v1/themes/random",
{
headers: { Authorization: `Bearer ${token}` },
credentials: "include",
}
);
const response = await getRandomThemes();
if (response.ok) {
const data = await response.json();
setRandomTheme(data);
@ -86,15 +79,7 @@ export default function ThemeSlaughter() {
if (!token) return; // Wait until token is available
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/voteSlaughter"
: "http://localhost:3005/api/v1/themes/voteSlaughter",
{
headers: { Authorization: `Bearer ${token}` },
credentials: "include",
}
);
const response = await getSlaughterThemes();
if (response.ok) {
const data = await response.json();
setVotedThemes(data);
@ -114,23 +99,7 @@ export default function ThemeSlaughter() {
setThemeLoading((prev) => ({ ...prev, [randomTheme.id]: true }));
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/voteSlaughter"
: "http://localhost:3005/api/v1/themes/voteSlaughter",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
credentials: "include",
body: JSON.stringify({
suggestionId: randomTheme.id,
voteType,
}),
}
);
const response = await postThemeSlaughterVote(randomTheme.id, voteType);
if (response.ok) {
// Refresh data after voting

View file

@ -9,6 +9,7 @@ import {
} from "@/helpers/jam";
import { ThemeType } from "@/types/ThemeType";
import { joinJam } from "@/helpers/jam";
import { deleteThemeSuggestion, getThemeSuggestions, postThemeSuggestion } from "@/requests/theme";
export default function ThemeSuggestions() {
const [suggestion, setSuggestion] = useState("");
@ -44,15 +45,7 @@ export default function ThemeSuggestions() {
// Fetch all suggestions for the logged-in user
const fetchSuggestions = async () => {
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/suggestion"
: "http://localhost:3005/api/v1/themes/suggestion",
{
headers: { Authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
const response = await getThemeSuggestions();
if (response.ok) {
const data = await response.json();
setUserSuggestions(data);
@ -89,20 +82,7 @@ export default function ThemeSuggestions() {
throw new Error("User is not authenticated. Please log in.");
}
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/suggestion"
: "http://localhost:3005/api/v1/themes/suggestion",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
credentials: "include",
body: JSON.stringify({ suggestionText: suggestion }),
}
);
const response = await postThemeSuggestion(suggestion);
if (!response.ok) {
const errorData = await response.json();
@ -128,18 +108,7 @@ export default function ThemeSuggestions() {
// Handle deleting a suggestion
const handleDelete = async (id: number) => {
try {
const token = getCookie("token");
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? `https://d2jam.com/api/v1/themes/suggestion/${id}`
: `http://localhost:3005/api/v1/themes/suggestion/${id}`,
{
method: "DELETE",
headers: { Authorization: `Bearer ${token}` },
credentials: "include",
}
);
const response = await deleteThemeSuggestion(id);
if (!response.ok) {
throw new Error("Failed to delete suggestion.");

View file

@ -9,6 +9,7 @@ import {
} from "@/helpers/jam";
import { ThemeType } from "@/types/ThemeType";
import { joinJam } from "@/helpers/jam";
import { getThemeVotes, getTopThemes, postThemeSuggestionVote } from "@/requests/theme";
interface VoteType {
themeSuggestionId: number;
@ -46,28 +47,12 @@ export default function VotingPage() {
if (!token || !activeJamResponse) return;
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/top-themes"
: "http://localhost:3005/api/v1/themes/top-themes",
{
headers: { Authorization: `Bearer ${token}` },
credentials: "include",
}
);
const response = await getTopThemes();
if (response.ok) {
const themes = await response.json();
// Fetch user's votes for these themes
const votesResponse = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/votes"
: "http://localhost:3005/api/v1/themes/votes",
{
headers: { Authorization: `Bearer ${token}` },
credentials: "include",
}
);
const votesResponse = await getThemeVotes();
if (votesResponse.ok) {
const votes = await votesResponse.json();
@ -103,20 +88,7 @@ export default function VotingPage() {
);
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/themes/vote"
: "http://localhost:3005/api/v1/themes/vote",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
credentials: "include",
body: JSON.stringify({ suggestionId: themeId, votingScore }),
}
);
const response = await postThemeSuggestionVote(themeId, votingScore);
if (response.ok) {
setThemes((prevThemes) =>

View file

@ -1,6 +1,7 @@
import { JamType } from "@/types/JamType";
import { getCookie } from "./cookie";
import { toast } from "react-toastify";
import * as jamRequests from '@/requests/jam'
export interface ActiveJamResponse {
phase: string;
@ -8,23 +9,13 @@ export interface ActiveJamResponse {
}
export async function getJams(): Promise<JamType[]> {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/jams"
: "http://localhost:3005/api/v1/jams"
);
const response = await jamRequests.getJams();
return response.json();
}
export async function getCurrentJam(): Promise<ActiveJamResponse | null> {
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/jams/active"
: "http://localhost:3005/api/v1/jams/active"
);
const response = await jamRequests.getCurrentJam();
const data = await response.json();
return {
@ -38,23 +29,7 @@ export async function getCurrentJam(): Promise<ActiveJamResponse | null> {
}
export async function joinJam(jamId: number) {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/join-jam"
: "http://localhost:3005/api/v1/join-jam",
{
body: JSON.stringify({
jamId: jamId,
userSlug: getCookie("user"),
}),
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
}
);
const response = await jamRequests.joinJam(jamId);
if (response.status == 401) {
toast.error("You have already joined the jam");
@ -70,17 +45,7 @@ export async function joinJam(jamId: number) {
export async function hasJoinedCurrentJam(): Promise<boolean> {
try {
const response = await fetch(
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1/jams/participation"
: "http://localhost:3005/api/v1/jams/participation",
{
credentials: "include",
headers: {
Authorization: `Bearer ${getCookie("token")}`,
},
}
);
const response = await jamRequests.hasJoinedCurrentJam();
return response.ok;
} catch (error) {

27
src/requests/auth.ts Normal file
View file

@ -0,0 +1,27 @@
import { BASE_URL } from "./config";
export async function signup(username: string, password: string) {
return fetch(`${BASE_URL}/signup`, {
body: JSON.stringify({ username, password }),
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
}
);
}
export async function login(username: string, password: string) {
return fetch(`${BASE_URL}/login`, {
method: "POST",
body: JSON.stringify({ username, password }),
headers: { "Content-Type": "application/json" },
credentials: "include",
});
}
export async function logout() {
return fetch(`${BASE_URL}/logout`, {
method: "POST",
credentials: "include"
});
}

19
src/requests/comment.ts Normal file
View file

@ -0,0 +1,19 @@
import { getCookie } from "@/helpers/cookie";
import { BASE_URL } from "./config";
export async function postComment(content: string, postId: number) {
return fetch(`${BASE_URL}/comment`, {
body: JSON.stringify({
content,
postId,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
}

4
src/requests/config.ts Normal file
View file

@ -0,0 +1,4 @@
export const BASE_URL =
process.env.NEXT_PUBLIC_MODE === "PROD"
? "https://d2jam.com/api/v1"
: "http://localhost:3005/api/v1";

84
src/requests/game.ts Normal file
View file

@ -0,0 +1,84 @@
import { getCookie } from "@/helpers/cookie"
import { BASE_URL } from "./config"
import { PlatformType } from "@/types/DownloadLinkType";
export async function getCurrentGame() {
return fetch(`${BASE_URL}/self/current-game?username=${getCookie("user")}`, {
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
}
export async function getGame(gameSlug: string) {
return fetch(`${BASE_URL}/games/${gameSlug}`, {
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
}
export async function postGame(
title: string,
gameSlug: string,
description: string,
thumbnail: string,
downloadLinks: {
url: string;
platform: PlatformType;
}[],
userSlug: string,
contributors: number[]
) {
return fetch(`${BASE_URL}/games/create`, {
body: JSON.stringify({
name: title,
slug: gameSlug,
description,
thumbnail,
downloadLinks,
userSlug,
contributors,
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
}
export async function updateGame(
previousGameSlug: string,
title: string,
gameSlug: string,
description: string,
thumbnail: string,
downloadLinks: {
url: string;
platform: PlatformType;
}[],
userSlug: string,
contributors: number[]
) {
return fetch(`${BASE_URL}/games/${previousGameSlug}`, {
body: JSON.stringify({
name: title,
slug: gameSlug,
description,
thumbnail,
downloadLinks,
userSlug,
contributors,
}),
method: "PUT",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
}

34
src/requests/jam.ts Normal file
View file

@ -0,0 +1,34 @@
import { getCookie } from "@/helpers/cookie";
import { BASE_URL } from "./config";
export async function getJams() {
return fetch(`${BASE_URL}/jams`);
}
export async function getCurrentJam() {
return fetch(`${BASE_URL}/jams/active`);
}
export async function joinJam(jamId: number) {
return fetch(`${BASE_URL}/join-jam`, {
body: JSON.stringify({
jamId: jamId,
userSlug: getCookie("user"),
}),
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
});
}
export async function hasJoinedCurrentJam() {
return fetch(`${BASE_URL}/jams/participation`, {
credentials: "include",
headers: {
Authorization: `Bearer ${getCookie("token")}`,
},
});
}

18
src/requests/like.ts Normal file
View file

@ -0,0 +1,18 @@
import { getCookie } from "@/helpers/cookie";
import { BASE_URL } from "./config";
export async function postLike(parentId: number, isComment: boolean) {
return fetch(`${BASE_URL}/like`, {
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
body: JSON.stringify({
username: getCookie("user"),
postId: !isComment ? parentId : 0,
commentId: isComment ? parentId : 0,
}),
});
}

42
src/requests/mod.ts Normal file
View file

@ -0,0 +1,42 @@
import { getCookie } from "@/helpers/cookie";
import { BASE_URL } from "./config";
export async function assignMod(userSlug: string, mod: boolean) {
return fetch(`${BASE_URL}/mod`, {
body: JSON.stringify({
targetname: userSlug,
mod,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
}
export async function assignAdmin(userSlug: string, admin: boolean) {
if (!admin) return assignMod(userSlug, true);
return fetch(`${BASE_URL}/mod`, {
body: JSON.stringify({
targetname: userSlug,
admin: true,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
}

77
src/requests/post.ts Normal file
View file

@ -0,0 +1,77 @@
import { getCookie } from "@/helpers/cookie";
import { BASE_URL } from "./config";
import { PostTime } from "@/types/PostTimes";
export async function getPosts(sort: string, time: PostTime, sticky: boolean, tagRules?: { [key: number]: number }, userSlug?: string) {
let url = `${BASE_URL}/posts?sort=${sort}&time=${time}`;
if (sticky) url += '&sticky=true';
if (userSlug) url += `&user=${userSlug}`;
if (tagRules) url += `&tags=${
Object.entries(tagRules)
.map((key) => `${key}`)
.join("_")
}`;
return fetch(url);
}
export async function getPost(postSlug: string, userSlug?: string) {
let url = `${BASE_URL}/post?slug=${postSlug}`;
if (userSlug) url += `&user=${userSlug}`;
return fetch(url);
}
export async function postPost(title: string, content: string, sticky: boolean, tags: (number | undefined)[]) {
return fetch(`${BASE_URL}/post`, {
body: JSON.stringify({
title,
content,
sticky,
username: getCookie("user"),
tags,
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
}
);
}
export async function deletePost(postId: number) {
return fetch(`${BASE_URL}/post`, {
body: JSON.stringify({
postId,
username: getCookie("user"),
}),
method: "DELETE",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
});
}
export async function stickPost(postId: number, sticky: boolean) {
return fetch(`${BASE_URL}/post/sticky`, {
body: JSON.stringify({
postId,
sticky,
username: getCookie("user"),
}),
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie(
"token"
)}`,
},
credentials: "include",
}
);
}

5
src/requests/streamer.ts Normal file
View file

@ -0,0 +1,5 @@
import { BASE_URL } from "./config";
export async function getStreamers() {
return fetch(`${BASE_URL}/streamers/get`);
}

5
src/requests/tag.ts Normal file
View file

@ -0,0 +1,5 @@
import { BASE_URL } from "./config";
export async function getTags() {
return fetch(`${BASE_URL}/tags`);
}

86
src/requests/theme.ts Normal file
View file

@ -0,0 +1,86 @@
import { getCookie } from "@/helpers/cookie";
import { BASE_URL } from "./config";
export async function getThemeSuggestions() {
return fetch(`${BASE_URL}/themes/suggestion`, {
headers: { Authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
});
}
export async function getTopThemes() {
return fetch(`${BASE_URL}/themes/top-themes`, {
headers: { Authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
});
}
export async function getRandomThemes() {
return fetch(`${BASE_URL}/themes/random`, {
headers: { Authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
});
}
export async function getSlaughterThemes() {
return fetch(`${BASE_URL}/themes/voteSlaughter`, {
headers: { Authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
});
}
export async function getThemeVotes() {
return fetch(`${BASE_URL}/themes/votes`, {
headers: { Authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
}
);
}
export async function postThemeSuggestion(suggestion: string) {
return fetch(`${BASE_URL}/themes/suggestion`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
body: JSON.stringify({ suggestionText: suggestion }),
});
}
export async function deleteThemeSuggestion(suggestionId: number) {
return fetch(`${BASE_URL}/themes/suggestion/${suggestionId}`, {
method: "DELETE",
headers: { Authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
});
}
export async function postThemeSuggestionVote(suggestionId: number, votingScore: number) {
return fetch(`${BASE_URL}/themes/vote`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
body: JSON.stringify({ suggestionId, votingScore }),
});
}
export async function postThemeSlaughterVote(suggestionId: number, voteType: string) {
return fetch(`${BASE_URL}/themes/voteSlaughter`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getCookie("token")}`,
},
credentials: "include",
body: JSON.stringify({
suggestionId,
voteType,
}),
}
);
}

39
src/requests/user.ts Normal file
View file

@ -0,0 +1,39 @@
import { getCookie, hasCookie } from "@/helpers/cookie";
import { BASE_URL } from "./config";
export async function getSelf() {
return fetch(`${BASE_URL}/self?username=${getCookie("user")}`, {
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
});
}
export async function getUser(userSlug: string) {
return fetch(`${BASE_URL}/user?slug=${userSlug}`);
}
export async function searchUsers(query: string) {
return fetch(`${BASE_URL}/user/search?q=${query}`, {
headers: { authorization: `Bearer ${getCookie("token")}` },
credentials: "include",
});
}
export async function updateUser(userSlug: string, name: string, bio: string, profilePicture: string, bannerPicture: string) {
return fetch(`${BASE_URL}/user`, {
body: JSON.stringify({
slug: userSlug,
name,
bio,
profilePicture: profilePicture,
bannerPicture: bannerPicture,
}),
method: "PUT",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${getCookie("token")}`,
},
}
);
}