Skip to content

Commit

Permalink
cookie clicker
Browse files Browse the repository at this point in the history
  • Loading branch information
docimin committed Nov 11, 2023
1 parent 74a05ed commit b98a139
Show file tree
Hide file tree
Showing 4 changed files with 163 additions and 53 deletions.
2 changes: 1 addition & 1 deletion app/api/fun/pats/[uniqueId]/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
31 changes: 31 additions & 0 deletions app/api/fun/pats/route.js
Original file line number Diff line number Diff line change
@@ -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 }
);
}
}
37 changes: 37 additions & 0 deletions app/api/fun/pats/update/[uniqueId]/route.js
Original file line number Diff line number Diff line change
@@ -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 });
}
}
146 changes: 94 additions & 52 deletions app/pat/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<>
<div>User ID: {userId}</div>
<div>Pat Count: {patCount}</div>
<div>Total Count: {totalCount}</div>
<button onClick={handleIncrement}>Add Increment</button>
</>
);
}

0 comments on commit b98a139

Please sign in to comment.