Skip to content

Commit

Permalink
Update API routes and fix user settings
Browse files Browse the repository at this point in the history
  • Loading branch information
docimin committed Nov 23, 2023
1 parent c5deeaf commit 32d60f2
Show file tree
Hide file tree
Showing 7 changed files with 162 additions and 106 deletions.
110 changes: 70 additions & 40 deletions src/app/account/frontpage/page.client.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand All @@ -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) {
Expand All @@ -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();
Expand All @@ -75,50 +65,81 @@ 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", {
method: "GET",
});

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) {
Expand All @@ -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 (
Expand Down Expand Up @@ -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
/>
<div className="absolute inset-y-0 right-0 pr-3 flex items-center text-sm leading-5">
<span aria-disabled className="text-gray-400 select-none">
<span
aria-disabled
className="text-gray-400 select-none mr-6"
>
DD/MM/YYYY
</span>{" "}
</div>
Expand Down
29 changes: 17 additions & 12 deletions src/app/account/page.client.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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);
}
}
};
Expand Down Expand Up @@ -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}
/>
</div>
Expand Down
37 changes: 12 additions & 25 deletions src/app/account/socials/page.client.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 || "",
Expand All @@ -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();
Expand Down
19 changes: 0 additions & 19 deletions src/app/account/test/page.jsx

This file was deleted.

45 changes: 45 additions & 0 deletions src/app/api/user/avatarChange/[uniqueId]/route.js
Original file line number Diff line number Diff line change
@@ -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 });
}
}
Loading

0 comments on commit 32d60f2

Please sign in to comment.