From 32d60f2dc8066961787d94b77f38d852433d216f Mon Sep 17 00:00:00 2001 From: Faye Date: Thu, 23 Nov 2023 03:21:21 +0100 Subject: [PATCH] Update API routes and fix user settings --- src/app/account/frontpage/page.client.jsx | 110 +++++++++++------- src/app/account/page.client.jsx | 29 +++-- src/app/account/socials/page.client.jsx | 37 ++---- src/app/account/test/page.jsx | 19 --- .../api/user/avatarChange/[uniqueId]/route.js | 45 +++++++ .../api/user/editUserData/[uniqueId]/route.js | 26 +++-- .../user/handleNsfwChange/[uniqueId]/route.js | 2 +- 7 files changed, 162 insertions(+), 106 deletions(-) delete mode 100644 src/app/account/test/page.jsx create mode 100644 src/app/api/user/avatarChange/[uniqueId]/route.js diff --git a/src/app/account/frontpage/page.client.jsx b/src/app/account/frontpage/page.client.jsx index 8deeaad6..8f13bb72 100644 --- a/src/app/account/frontpage/page.client.jsx +++ b/src/app/account/frontpage/page.client.jsx @@ -21,20 +21,10 @@ export default function AccountPage() { const fetchData = async () => { setIsLoading(true); try { - const userResponse = await fetch("/api/user/getUserSelf", { + const userDataResponse = await fetch(`/api/user/getUserDataSelf`, { method: "GET", }); - const userResponseData = await userResponse.json(); - const userId = userResponseData.id; - - const userDataResponse = await fetch( - `/api/user/getUserDataSelf`, - { - method: "GET", - } - ); - const userDataResponseData = await userDataResponse.json(); //console.log(userDataResponseData.data.attributes); setUserData({ @@ -45,8 +35,8 @@ export default function AccountPage() { pronouns: userDataResponseData.documents[0].pronouns || "", location: userDataResponseData.documents[0].location || "", avatar: - userDataResponseData.documents[0].avatar?.data?.attributes - ?.url || "/logos/logo.webp", // Set the avatar value or a placeholder image + userDataResponseData.documents[0].avatar?.data?.attributes?.url || + "/logos/logo.webp", // Set the avatar value or a placeholder image }); setIsLoading(false); } catch (error) { @@ -61,7 +51,7 @@ export default function AccountPage() { const handleAvatarChange = (event) => { const selectedFile = event.target.files[0]; if (selectedFile.size > 2 * 1024 * 1024) { - alert("File size must be less than 2 MB."); + alert("Dateigröße darf nur bis 2MB groß sein."); return; } const fileReader = new FileReader(); @@ -75,17 +65,17 @@ export default function AccountPage() { if (img.width <= 1024 && img.height <= 1024) { setSelectedFile(selectedFile); } else { - alert("Image resolution darf nur bis 1024x1024 pixel groß sein."); + alert("Bild darf nur bis 1024x1024 pixel groß sein."); } }; }; }; - const handleSubmit = async (event) => { + const handleSubmitAVatar = async (event) => { event.preventDefault(); const formData = new FormData(); - formData.append("files.avatar", selectedFile); + formData.append("file", selectedFile); try { const userResponse = await fetch("/api/user/getUserSelf", { @@ -93,32 +83,63 @@ export default function AccountPage() { }); const userResponseData = await userResponse.json(); - const userId = userResponseData.id; + const userId = userResponseData[0].$id; // Year-Month-Day (YYYY-MM-DD) - formData.append( - "data", - JSON.stringify({ - users_permissions_user: userId, - status: document.getElementById("status").value, - bio: document.getElementById("biostatus").value, - displayname: document.getElementById("displayname").value, - birthday: document.getElementById("birthday").value, - pronouns: document.getElementById("pronouns").value, - location: document.getElementById("location").value, - }) - ); + setIsUploading(true); // Set isUploading to true before making the API call + + const response = await fetch(`/api/user/avatarChange/${userId}`, { + method: "POST", + body: formData, + }); + + const responseData = await response.json(); + if (response.ok) { + //console.log("File uploaded successfully"); + setIsUploading(false); // Set isUploading to false after the API call is complete + // Reload the window + alert("Saved!"); + window.location.reload(); + } + } catch (error) { + console.error(error); + } + }; + + const handleSubmit = async (event) => { + event.preventDefault(); + + //const formData = new FormData(); + //formData.append("file", selectedFile); + + try { + const userResponse = await fetch("/api/user/getUserSelf", { + method: "GET", + }); + + const userResponseData = await userResponse.json(); + const userId = userResponseData[0].$id; + + // Year-Month-Day (YYYY-MM-DD) setIsUploading(true); // Set isUploading to true before making the API call - const response = await fetch( - `/api/user/editUserData/${userId}?populate=*`, - { - method: "PUT", - body: formData, - } - ); + const response = await fetch(`/api/user/editUserData/${userId}`, { + method: "PATCH", + body: JSON.stringify({ + data: { + status: document.getElementById("status").value, + bio: document.getElementById("biostatus").value, + displayname: document.getElementById("displayname").value, + birthday: new Date(document.getElementById("birthday").value) + .toISOString() + .split("T")[0], + pronouns: document.getElementById("pronouns").value, + location: document.getElementById("location").value, + }, + }), + }); const responseData = await response.json(); if (response.ok) { @@ -127,7 +148,7 @@ export default function AccountPage() { setUserData(responseData); // Set the userData state with the response data // Reload the window //alert("Saved!"); - window.location.reload(); + //window.location.reload(); } else { // Check for the specific error structure if ( @@ -326,13 +347,22 @@ export default function AccountPage() { name="birthday" type="date" className="block w-full rounded-md border-0 bg-white/5 py-1.5 shadow-sm ring-1 ring-inset dark:ring-white/10 ring-black/10 focus:ring-2 focus:ring-inset focus:ring-indigo-500 sm:text-sm sm:leading-6" - value={userData.birthday} // Set the value from state + value={ + userData.birthday + ? new Date(userData.birthday) + .toISOString() + .split("T")[0] + : "" + } // Set the value from state in the correct format onChange={(e) => { setUserData({ ...userData, birthday: e.target.value }); }} // Update state when the input changes />
- + DD/MM/YYYY {" "}
diff --git a/src/app/account/page.client.jsx b/src/app/account/page.client.jsx index 92e11e78..8e4c99da 100644 --- a/src/app/account/page.client.jsx +++ b/src/app/account/page.client.jsx @@ -111,24 +111,23 @@ export default function AccountPage() { const handleNsfwChange = async (event) => { const { checked } = event.target; + setUserData((prevUserData) => ({ ...prevUserData, enablensfw: checked, })); - const isChecked = event.target.checked; - setNsfw(isChecked); - - const userResponse = await fetch("/api/user/getUserSelf", { - method: "GET", - }); - const userResponseData = await userResponse.json(); - setUserMe(userResponseData[0]); - const userId = userResponseData[0].$id; + const isChecked = checked; // Save the value before async operations try { + const userResponse = await fetch("/api/user/getUserSelf", { + method: "GET", + }); + const userResponseData = await userResponse.json(); + const userId = userResponseData[0].$id; + const putResponse = await fetch(`/api/user/handleNsfwChange/${userId}`, { - method: "PUT", + method: "PATCH", body: JSON.stringify({ data: { enablensfw: isChecked, @@ -139,11 +138,17 @@ export default function AccountPage() { if (!putResponse.ok) { throw new Error("PUT request failed"); } + + // Update userMe state after successful request + setUserMe((prevUserMe) => ({ + ...prevUserMe, + enablensfw: isChecked, + })); } catch (error) { console.error(error.message); if (error.response) { const response = await error.response.json(); - //console.log(response); + // console.log(response); } } }; @@ -316,7 +321,7 @@ export default function AccountPage() { name="nsfwtoggle" type="checkbox" className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-600" - checked={userData.enablensfw} + checked={userMe?.enablensfw} onChange={handleNsfwChange} /> diff --git a/src/app/account/socials/page.client.jsx b/src/app/account/socials/page.client.jsx index af524329..530053f9 100644 --- a/src/app/account/socials/page.client.jsx +++ b/src/app/account/socials/page.client.jsx @@ -18,19 +18,13 @@ export default function AccountPage() { const fetchData = async () => { setIsLoading(true); try { - const userResponse = await fetch("/api/user/getUserSelf", { - method: "GET", - }); - - const userResponseData = await userResponse.json(); - const userDataResponse = await fetch(`/api/user/getUserDataSelf`, { method: "GET", }); const userDataResponseData = await userDataResponse.json(); const userData = userDataResponseData.documents[0]; - + setUserData({ discordname: userData.discordname || "", telegramname: userData.telegramname || "", @@ -57,28 +51,21 @@ export default function AccountPage() { }); const userResponseData = await userResponse.json(); - const userId = userResponseData.id; - - const formData = new FormData(); - - // Append the data for Discord, Telegram, and Furaffinity - formData.append( - "data", - JSON.stringify({ - users_permissions_user: userId, - discordname: document.getElementById("discordname").value, - telegramname: document.getElementById("telegramname").value, - furaffinityname: document.getElementById("furaffinityname").value, - X_name: document.getElementById("X_name").value, - twitchname: document.getElementById("twitchname").value, - }) - ); + const userId = userResponseData[0].$id; setIsUploading(true); const response = await fetch(`/api/user/editUserData/${userId}`, { - method: "PUT", - body: formData, + method: "PATCH", + body: JSON.stringify({ + data: { + discordname: document.getElementById("discordname").value, + telegramname: document.getElementById("telegramname").value, + furaffinityname: document.getElementById("furaffinityname").value, + X_name: document.getElementById("X_name").value, + twitchname: document.getElementById("twitchname").value, + }, + }), }); const responseData = await response.json(); diff --git a/src/app/account/test/page.jsx b/src/app/account/test/page.jsx deleted file mode 100644 index 82de0004..00000000 --- a/src/app/account/test/page.jsx +++ /dev/null @@ -1,19 +0,0 @@ -"use client"; - -import { useEffect } from "react"; - -export default function AccountSettings() { - useEffect( - () => async () => { - const getJWT = await fetch("/api/user/createJWT", { - method: "POST", - }); - - const getJWTData = await getJWT.json(); - console.log(getJWTData); - }, - [] - ); - - return <>Test; -} diff --git a/src/app/api/user/avatarChange/[uniqueId]/route.js b/src/app/api/user/avatarChange/[uniqueId]/route.js new file mode 100644 index 00000000..90070510 --- /dev/null +++ b/src/app/api/user/avatarChange/[uniqueId]/route.js @@ -0,0 +1,45 @@ +import { NextResponse } from "next/server"; +import { headers } from "next/headers"; + +export const runtime = "edge"; + +export async function POST(request) { + try { + const headersList = headers(); + const cookieHeader = headersList.get("cookie"); + + // Assume the last segment of the URL is the user ID + const userId = request.url.split("/").pop(); + + const requestData = await request.arrayBuffer(); + + if (!userId) { + throw new Error("User ID is required"); + } + + // Construct the URL for the external fetch + const fetchURL = `${process.env.NEXT_PUBLIC_DOMAIN_API}/api/user-data/${userId}`; + const uploadUrl = `${process.env.NEXT_PUBLIC_DOMAIN_API}/v1/storage/buckets/655842922bac16a94a25/files`; + + const response = await fetch(fetchURL, { + method: "POST", + headers: { + "X-Appwrite-Project": `${process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID}`, + "X-Appwrite-Response-Format": "1.4.0", + "Content-Type": + request.headers.get("Content-Type") || "multipart/form-data", + Cookie: cookieHeader, + }, + body: requestData, + }); + + 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/src/app/api/user/editUserData/[uniqueId]/route.js b/src/app/api/user/editUserData/[uniqueId]/route.js index 80dbc490..9f8176bd 100644 --- a/src/app/api/user/editUserData/[uniqueId]/route.js +++ b/src/app/api/user/editUserData/[uniqueId]/route.js @@ -1,31 +1,39 @@ import { NextResponse } from "next/server"; +import { headers } from "next/headers"; export const runtime = "edge"; -export async function PUT(request) { +export async function PATCH(request) { try { + const headersList = headers(); + const cookieHeader = headersList.get("cookie"); + // Assume the last segment of the URL is the user ID const userId = request.url.split("/").pop(); - const requestData = await request.arrayBuffer(); - + // get request json + const requestBody = await request.json(); + if (!userId) { - throw new Error("User ID is required"); + return NextResponse.json("User ID is required", { status: 400 }); } // Construct the URL for the external fetch - const fetchURL = `${process.env.NEXT_PUBLIC_DOMAIN_API}/api/user-data/${userId}`; + const fetchURL = `${process.env.NEXT_PUBLIC_API_URL}/v1/databases/65527f2aafa5338cdb57/collections/65564fa28d1942747a72/documents/${userId}`; const response = await fetch(fetchURL, { - method: "PUT", + method: "PATCH", headers: { - Authorization: `Bearer ${process.env.DOMAIN_API_KEY}`, - "Content-Type": request.headers.get("Content-Type") || "multipart/form-data", + "Content-Type": "application/json", + "X-Appwrite-Project": `${process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID}`, + "X-Appwrite-Response-Format": "1.4.0", + Cookie: cookieHeader, }, - body: requestData, + body: JSON.stringify(requestBody), }); if (!response.ok) { + console.log(response.status, response.statusText); throw new Error("Failed to update data"); } diff --git a/src/app/api/user/handleNsfwChange/[uniqueId]/route.js b/src/app/api/user/handleNsfwChange/[uniqueId]/route.js index 958659bc..aca1fb21 100644 --- a/src/app/api/user/handleNsfwChange/[uniqueId]/route.js +++ b/src/app/api/user/handleNsfwChange/[uniqueId]/route.js @@ -3,7 +3,7 @@ import { headers } from "next/headers"; export const runtime = "edge"; -export async function PUT(request) { +export async function PATCH(request) { try { const headersList = headers(); const cookieHeader = headersList.get("cookie");