Member page

This commit is contained in:
cdricms
2025-02-05 09:11:17 +01:00
parent 0595f5dba7
commit 09b0c9b142
12 changed files with 372 additions and 95 deletions

View File

@@ -1,60 +1,9 @@
"use client";
import { API_URL } from "@/lib/constants";
import { getCookie } from "cookies-next";
import request from "@/lib/request";
import { ApiResponse } from "@/types/types";
import useSWR, { SWRConfiguration } from "swr";
import useSWRMutation, { type SWRMutationConfiguration } from "swr/mutation";
export interface ApiResponse<T> {
status: "Error" | "Success";
message: string;
data?: T;
}
export async function request<T>(
endpoint: string,
options: {
method?: "GET" | "POST" | "PATCH" | "DELETE";
body?: any;
requiresAuth?: boolean;
csrfToken?: boolean;
} = {},
): Promise<ApiResponse<T>> {
const { method = "GET", body, requiresAuth = true } = options;
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (options.csrfToken) {
const res: ApiResponse<{ csrf: string }> = await (
await fetch(`${API_URL}/csrf-token`)
).json();
if (res.data) headers["X-CSRF-Token"] = res.data.csrf;
}
if (requiresAuth) {
const authToken = getCookie("auth_token");
if (!authToken) {
throw new Error("User is not authenticated");
}
headers.Authorization = `Bearer ${authToken}`;
}
const response = await fetch(`${API_URL}${endpoint}`, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
credentials: options.csrfToken ? "include" : "omit",
});
const apiResponse: ApiResponse<T> = await response.json();
if (apiResponse.status === "Error") {
throw new Error(apiResponse.message || "An unexpected error occurred");
}
return apiResponse;
}
async function fetcher<T>(
url: string,
requiresAuth: boolean = true,