diff --git a/app/api/fun/pats/[uniqueId]/route.js b/app/api/fun/pats/[uniqueId]/route.js index 821ee34f..9db818f9 100644 --- a/app/api/fun/pats/[uniqueId]/route.js +++ b/app/api/fun/pats/[uniqueId]/route.js @@ -8,7 +8,7 @@ export async function GET(request) { const userId = request.url.split("/").pop(); // Construct the URL for the external fetch - const fetchURL = `${process.env.NEXT_PUBLIC_DOMAIN_API}/api/pats?filters[users_permissions_user]=${userId}]`; + const fetchURL = `${process.env.NEXT_PUBLIC_DOMAIN_API}/api/pats?filters[users_permissions_user]=${userId}`; const response = await fetch(fetchURL, { method: "GET", diff --git a/app/api/fun/pats/route.js b/app/api/fun/pats/route.js new file mode 100644 index 00000000..c66bd0df --- /dev/null +++ b/app/api/fun/pats/route.js @@ -0,0 +1,31 @@ +import { NextResponse } from "next/server"; + +export const runtime = "edge"; + +export async function GET() { + try { + // Construct the URL for the external fetch + const fetchURL = `${process.env.NEXT_PUBLIC_DOMAIN_API}/api/pats`; + + const response = await fetch(fetchURL, { + method: "GET", + headers: { + Authorization: `Bearer ${process.env.DOMAIN_API_KEY}`, + "Content-Type": "application/json", + }, + }); + + if (!response.ok) { + throw new Error("Failed to fetch data"); + } + + const data = await response.json(); + return NextResponse.json(data, { status: 200 }); + } catch (error) { + console.error(error); + return NextResponse.json( + { error: "Internal Server Error" }, + { status: 500 } + ); + } +} diff --git a/app/api/fun/pats/update/[uniqueId]/route.js b/app/api/fun/pats/update/[uniqueId]/route.js new file mode 100644 index 00000000..37acfb50 --- /dev/null +++ b/app/api/fun/pats/update/[uniqueId]/route.js @@ -0,0 +1,37 @@ +import { NextResponse } from "next/server"; + +export const runtime = "edge"; + +export async function PUT(request) { + try { + // Assume the last segment of the URL is the user ID + const patId = request.url.split("/").pop(); + + const requestBody = await request.json(); + + if (!patId) { + throw new Error("Pat ID is required"); + } + + // Construct the URL for the external fetch + const fetchURL = `${process.env.NEXT_PUBLIC_DOMAIN_API}/api/pats/${patId}`; + + const response = await fetch(fetchURL, { + method: "PUT", + headers: { + Authorization: `Bearer ${process.env.DOMAIN_API_KEY}`, + "Content-Type": "application/json", + }, + body: JSON.stringify(requestBody), // Serialize requestBody to JSON + }); + + if (!response.ok) { + throw new Error("Failed to update data"); + } + + const data = await response.json(); + return NextResponse.json(data, { status: 200 }); + } catch (error) { + return NextResponse.json(error.message, { status: 500 }); + } +} diff --git a/app/pat/page.jsx b/app/pat/page.jsx index 1e3d5b05..7362f7c7 100644 --- a/app/pat/page.jsx +++ b/app/pat/page.jsx @@ -4,88 +4,130 @@ import { useEffect, useState } from "react"; export default function Home() { const [userId, setUserId] = useState(null); const [patCount, setPatCount] = useState(null); + const [totalCount, setTotalCount] = useState(null); useEffect(() => { const fetchData = async () => { try { - // Check if JWT cookie exists const jwtCookie = document.cookie.replace( /(?:(?:^|.*;\s*)jwt\s*=\s*([^;]*).*$)|^.*$/, "$1" ); - if (!jwtCookie || userId) { - // If JWT cookie doesn't exist or data has already been fetched, return - return; - } - // Fetch user data - const userResponse = await fetch("/api/user/getUserSelf", { - method: "GET", - }); - const userData = await userResponse.json(); - - if (!userData) { - return; - } + // Fetch data from /api/fun/pats regardless of whether the user is logged in + const patsResponse = await fetch("/api/fun/pats"); + const patsData = await patsResponse.json(); - // Extract user ID - const { id } = userData; + // Calculate the total count from the fetched data + const totalCount = patsData.data.reduce( + (acc, pat) => acc + Number(pat.attributes.count), + 0 + ); - // Fetch pat count using user ID - const patResponse = await fetch(`/api/fun/pats/${id}`, { - method: "GET", - }); + // Update state + setTotalCount(totalCount); - // Check if the data array is null or empty - const patData = await patResponse.json(); + if (jwtCookie) { + // If JWT cookie exists, fetch user-specific data + const userResponse = await fetch("/api/user/getUserSelf", { + method: "GET", + }); + const userData = await userResponse.json(); - if (patData.data && patData.data.length === 0) { - // Make a POST request to create data if no records are found - console.log("Creating pat count data"); - await fetch("/api/fun/pats/create", { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ - data: { - users_permissions_user: id, - }, - }), + if (!userData) { + return; + } + + // Extract user ID + const { id } = userData; + + // Fetch pat count using user ID + const patResponse = await fetch(`/api/fun/pats/${id}`, { + method: "GET", }); - } - // Fetch pat count again - console.log("Fetching updated pat count data"); - const updatedPatResponse = await fetch(`/api/fun/pats/${id}`, { - headers: { - Authorization: `Bearer ${jwtCookie}`, - }, - }); - const updatedPatData = await updatedPatResponse.json(); + const patData = await patResponse.json(); - // Extract pat count - const count = updatedPatData?.data[0]?.attributes?.count; + if (patData.data && patData.data.length === 0) { + await fetch("/api/fun/pats/create", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + data: { + users_permissions_user: id, + }, + }), + }); + } - // Update state - console.log("Before setting userId:", userId); + const updatedPatResponse = await fetch(`/api/fun/pats/${id}`, { + headers: { + Authorization: `Bearer ${jwtCookie}`, + }, + }); + const updatedPatData = await updatedPatResponse.json(); - setUserId(id); - console.log("Before setting userId:", userId); + const count = updatedPatData?.data[0]?.attributes?.count; - setPatCount(count); + setUserId(id); + setPatCount(count); + } } catch (error) { console.error("Error fetching data:", error); } }; fetchData(); - }, [userId]); // The effect now depends on userId + + const intervalId = setInterval(fetchData, 5000); + + return () => clearInterval(intervalId); + }, []); + + const handleIncrement = async () => { + try { + const currentPatResponse = await fetch(`/api/fun/pats/${userId}`); + const currentPatData = await currentPatResponse.json(); + const patId = currentPatData?.data[0]?.id; + + const currentCount = Number(currentPatData?.data[0]?.attributes?.count); + const newCount = currentCount + 1; + + await fetch(`/api/fun/pats/update/${patId}`, { + method: "PUT", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + data: { + count: newCount, + }, + }), + }); + + // Fetch the total count again and update the state + const updatedTotalResponse = await fetch("/api/fun/pats"); + const updatedTotalData = await updatedTotalResponse.json(); + const updatedTotalCount = updatedTotalData.data.reduce( + (acc, pat) => acc + Number(pat.attributes.count), + 0 + ); + + setTotalCount(updatedTotalCount); + setPatCount(newCount); + } catch (error) { + console.error("Error incrementing count:", error); + } + }; return ( <>
User ID: {userId}
Pat Count: {patCount}
+
Total Count: {totalCount}
+ ); }