Skip to content

Commit

Permalink
Merge pull request #6 from Ropold/front4
Browse files Browse the repository at this point in the history
Front4
  • Loading branch information
Ropold authored Feb 22, 2025
2 parents eeb97d4 + 45e0263 commit 37d460a
Show file tree
Hide file tree
Showing 17 changed files with 734 additions and 100 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,44 @@ public MemoryModel addMemory(
));
}

@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/avatar")
public MemoryModel addMemoryAvatar (@RequestBody MemoryModelDto memoryModelDto) {
return memoryService.addMemoryAvatar(
new MemoryModel(
null,
memoryModelDto.name(),
memoryModelDto.matchId(),
memoryModelDto.category(),
memoryModelDto.description(),
memoryModelDto.isActive(),
memoryModelDto.appUserGithubId(),
memoryModelDto.appUserUsername(),
memoryModelDto.appUserAvatarUrl(),
memoryModelDto.appUserGithubUrl(),
memoryModelDto.imageUrl()
));
}

@PutMapping("/avatar/{id}")
public MemoryModel updateMemoryAvatar(@PathVariable String id, @RequestBody MemoryModelDto memoryModelDto) {
return memoryService.updateMemoryAvatar(
id,
new MemoryModel(
id,
memoryModelDto.name(),
memoryModelDto.matchId(),
memoryModelDto.category(),
memoryModelDto.description(),
memoryModelDto.isActive(),
memoryModelDto.appUserGithubId(),
memoryModelDto.appUserUsername(),
memoryModelDto.appUserAvatarUrl(),
memoryModelDto.appUserGithubUrl(),
memoryModelDto.imageUrl()
));
}

@PutMapping("/{id}")
public MemoryModel updateMemory(
@PathVariable String id,
Expand Down
39 changes: 39 additions & 0 deletions backend/src/main/java/ropold/backend/service/MemoryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,45 @@ public MemoryModel toggleMemoryActive(String id) {
return memoryRepository.save(updatedMemoryModel);
}

public MemoryModel addMemoryAvatar(MemoryModel memoryModel) {
memoryModel = new MemoryModel(
idService.generateRandomId(),
memoryModel.name(),
memoryModel.matchId(),
memoryModel.category(),
memoryModel.description(),
memoryModel.isActive(),
memoryModel.appUserGithubId(),
memoryModel.appUserUsername(),
memoryModel.appUserAvatarUrl(),
memoryModel.appUserGithubUrl(),
memoryModel.imageUrl()
);
return memoryRepository.save(memoryModel);
}

public MemoryModel updateMemoryAvatar(String id, MemoryModel memoryModel) {
if (!memoryRepository.existsById(id)) {
throw new MemoryNotFoundException("No Memory found with ID: " + id);
}

MemoryModel updatedMemoryModel = new MemoryModel(
id,
memoryModel.name(),
memoryModel.matchId(),
memoryModel.category(),
memoryModel.description(),
memoryModel.isActive(),
memoryModel.appUserGithubId(),
memoryModel.appUserUsername(),
memoryModel.appUserAvatarUrl(),
memoryModel.appUserGithubUrl(),
memoryModel.imageUrl()
);
return memoryRepository.save(updatedMemoryModel);
}


//Not Used
public List<MemoryModel> getMemoriesByMatchId(int matchId) {
return memoryRepository.findAll().stream()
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export default function App() {
<Route path="*" element={<NotFound />} />
<Route path="/" element={<Home activeMemories={activeMemories} toggleFavorite={toggleFavorite} favorites={favorites} user={user} showSearch={showSearch} currentPage={currentPage} paginate={setCurrentPage}/>} />
<Route path="/play" element={<Play activeMemories={activeMemories} />} />
<Route path="/memory/:id" element={<Details allMemories={allMemories} />} />
<Route path="/memory/:id" element={<Details allMemories={allMemories} favorites={favorites} user={user} toggleFavorite={toggleFavorite}/>} />

<Route element={<ProtectedRoute user={user} />}>
<Route path="/favorites" element={<Favorites favorites={favorites} user={user} toggleFavorite={toggleFavorite}/>} />
Expand Down
106 changes: 67 additions & 39 deletions frontend/src/components/AddMemoryCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,19 @@ export default function AddMemoryCard(props: Readonly<MemoryCardProps>) {

// useEffect, um imageUrl zu setzen, wenn die Kategorie sich ändert und GitHub Avatar ausgewählt wird
useEffect(() => {
if (category === "GITHUB_AVATAR" && props.userDetails?.html_url) {
setImageUrl(props.userDetails.html_url); // Setze imageUrl auf die GitHub URL
if (category === "GITHUB_AVATAR" && props.userDetails?.avatar_url) {
setImageUrl(props.userDetails.avatar_url); // Setze imageUrl auf die GitHub URL
} else {
setImageUrl(""); // Leere das imageUrl bei anderen Kategorien
}
}, [category, props.userDetails?.html_url]); // Abhängig von der Kategorie und der GitHub-URL des Benutzers
}, [category, props.userDetails?.avatar_url]); // Abhängig von der Kategorie und der GitHub-URL des Benutzers

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();

const data = new FormData();

if (image) {
data.append("image", image);
}

const memoryData = {
name,
matchId: matchId, // matchId als number
matchId,
category,
description,
isActive: true,
Expand All @@ -56,35 +50,69 @@ export default function AddMemoryCard(props: Readonly<MemoryCardProps>) {
imageUrl: imageUrl,
};

data.append("memoryModelDto", new Blob([JSON.stringify(memoryData)], {type: "application/json"}));

console.log("memoryData:", memoryData);

axios
.post("/api/memory-hub", data, {
headers: {
"Content-Type": "multipart/form-data",
}
})
.then((response) => {
console.log("Antwort vom Server:", response.data);
navigate(`/memory/${response.data.id}`);
})
.catch((error) => {
if (error.response && error.response.status === 400 && error.response.data) {
const errorMessages = error.response.data;
const errors: string[] = [];
Object.keys(errorMessages).forEach((field) => {
errors.push(`${field}: ${errorMessages[field]}`);
});

setErrorMessages(errors);
setShowPopup(true);
} else {
alert("An unexpected error occurred. Please try again.");
}
});
}
if (category === "GITHUB_AVATAR") {
// JSON-POST an den Avatar-Endpunkt
axios
.post("/api/memory-hub/avatar", memoryData, {
headers: {
"Content-Type": "application/json",
}
})
.then((response) => {
console.log("Avatar Memory gespeichert:", response.data);
navigate(`/memory/${response.data.id}`);
})
.catch((error) => {
if (error.response && error.response.status === 400 && error.response.data) {
const errorMessages = error.response.data;
const errors: string[] = [];
Object.keys(errorMessages).forEach((field) => {
errors.push(`${field}: ${errorMessages[field]}`);
});

setErrorMessages(errors);
setShowPopup(true);
} else {
alert("An unexpected error occurred. Please try again.");
}
});
} else {
// Multipart-POST an den Standard-Endpunkt
const data = new FormData();

if (image) {
data.append("image", image);
}

data.append("memoryModelDto", new Blob([JSON.stringify(memoryData)], { type: "application/json" }));

axios
.post("/api/memory-hub", data, {
headers: {
"Content-Type": "multipart/form-data",
}
})
.then((response) => {
console.log("Memory gespeichert:", response.data);
navigate(`/memory/${response.data.id}`);
})
.catch((error) => {
if (error.response && error.response.status === 400 && error.response.data) {
const errorMessages = error.response.data;
const errors: string[] = [];
Object.keys(errorMessages).forEach((field) => {
errors.push(`${field}: ${errorMessages[field]}`);
});

setErrorMessages(errors);
setShowPopup(true);
} else {
alert("An unexpected error occurred. Please try again.");
}
});
}
};


const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files) {
Expand Down
69 changes: 54 additions & 15 deletions frontend/src/components/Details.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,76 @@
import { MemoryModel } from "./model/MemoryModel.ts";
import { useParams } from "react-router-dom";
import {DefaultMemory} from "./model/DefaultMemory.ts";
import "./styles/Details.css";
import "./styles/Profile.css";
import {useEffect, useState} from "react";
import axios from "axios";

type DetailsProps = {
allMemories: MemoryModel[];
favorites: string[];
user: string;
toggleFavorite: (memoryId: string) => void;
};


export default function Details(props: Readonly<DetailsProps>) {
const [memory, setMemory] = useState<MemoryModel>(DefaultMemory);
const { id } = useParams<{ id: string }>();

// Suche das Memory-Objekt mit der passenden ID
const memory = props.allMemories.find(mem => mem.id === id) || DefaultMemory;
const fetchMemoryDetails = () => {
if (!id) return;
axios
.get(`/api/memory-hub/${id}`)
.then((response) => setMemory(response.data))
.catch((error) => console.error("Error fetching memory details", error));
};

useEffect(() => {
fetchMemoryDetails();
}, [id]);

const isFavorite = props.favorites.includes(memory.id);

return (
<div>
{memory ? (
<div className="memory-details">
<h2>{memory.name}</h2>
<p><strong>Category:</strong> {memory.category}</p>
<p><strong>MatchId:</strong> {memory.matchId}</p>
<p><strong>Description:</strong> {memory.description || "No description available"}</p>


{memory.imageUrl && (
<img src={memory.imageUrl} alt={memory.name} className="memory-card-image" />
)}

{props.user !== "anonymousUser" && (
<div className="button-group">
<button
onClick={() => props.toggleFavorite(memory.id)}
className={isFavorite ? "favorite-on" : "favorite-off"}
>
</button>
</div>
)}

<div className="profile-container">
<h3>Memory added by GitHub User</h3>
<div>
<h3>{memory.name}</h3>
<p><strong>Category:</strong> {memory.category}</p>
<p><strong>Description:</strong> {memory.description}</p>
<p><strong>Active:</strong> {memory.isActive ? "Yes" : "No"}</p>
<p><strong>Username: </strong> {memory.appUserUsername}</p>
<p>
<strong>Created by:</strong>
<strong>GitHub Profile: </strong>
<a href={memory.appUserGithubUrl} target="_blank" rel="noopener noreferrer">
{memory.appUserUsername}
Visit Profile
</a>
</p>
<img src={memory.imageUrl} alt={memory.name} width={300} />
<img
src={memory.appUserAvatarUrl}
alt={`${memory.appUserUsername}'s avatar`}
className="user-avatar"
/>
</div>
) : (
<p>Memory not found.</p>
)}
</div>
</div>
);
}
Loading

0 comments on commit 37d460a

Please sign in to comment.