-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
227 lines (198 loc) · 6.96 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import express from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import cors from "cors";
import jwt from "jsonwebtoken";
import dotenv from "dotenv";
import path from "path";
import { fileURLToPath } from "url";
import { createProxyMiddleware } from "http-proxy-middleware";
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.use(cors());
app.use(bodyParser.json());
// Login route
app.post("/api/login", (req, res) => {
const { password } = req.body;
if (password === process.env.ADMIN_PASSWORD) {
// Generate a token
const token = jwt.sign({ role: "admin" }, process.env.JWT_SECRET, { expiresIn: "1h" });
return res.json({ token });
}
return res.status(401).json({ message: "Falsches Passwort" });
});
/**
* DB
*/
// Connect to MongoDB
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log("MongoDB connected"))
.catch((err) => console.error("MongoDB connection error:", err));
// Schema for Participants
const ParticipantSchema = new mongoose.Schema({
playerName: { type: String, required: true },
instrument: { type: String, required: true },
});
// Schema for Events
const EventSchema = new mongoose.Schema(
{
name: { type: String, required: true },
date: { type: Date, required: true },
time: { type: String },
finish: { type: String },
location: { type: String, required: true },
description: { type: String },
participants: [ParticipantSchema],
},
{
timestamps: true,
}
);
const Event = mongoose.model("Event", EventSchema);
/**
* CRUD API routes
*/
// POST /api/events
app.post("/api/events", async (req, res) => {
try {
const event = new Event(req.body);
const savedEvent = await event.save();
res.status(201).json(savedEvent);
} catch (error) {
console.error("Error creating event:", error);
res.status(500).json({ message: "Error creating event", error: error.message });
}
});
// GET /api/events
app.get("/api/events", async (req, res) => {
try {
const events = await Event.find();
res.status(200).json(events);
} catch (error) {
console.error("Error fetching events:", error);
res.status(500).json({ message: "Error fetching events", error: error.message });
}
});
// GET /api/events/:eventId
app.get("/api/events/:eventId", async (req, res) => {
const { eventId } = req.params;
if (!mongoose.Types.ObjectId.isValid(eventId)) {
return res.status(400).json({ message: "Invalid Event ID" });
}
try {
const event = await Event.findById(eventId);
if (!event) {
return res.status(404).json({ message: "Event not found" });
}
res.status(200).json(event);
} catch (error) {
console.error("Error fetching event:", error);
res.status(500).json({ message: "Error fetching event", error: error.message });
}
});
// PATCH /api/events/:eventId
app.patch("/api/events/:eventId", async (req, res) => {
const {eventId } = req.params;
if (!mongoose.Types.ObjectId.isValid(eventId)) {
return res.status(400).json({ message: "Invalid Event ID" });
}
try {
const updatedEvent = await Event.findByIdAndUpdate(eventId, { $set: req.body }, { new: true });
if (!updatedEvent) {
return res.status(404).json({ message: "Event not found" });
}
res.status(200).json(updatedEvent);
} catch (error) {
console.error("Error updating event:", error);
res.status(500).json({ message: "Error updating event", error: error.message });
}
});
// DELETE /api/events/:eventId
app.delete("/api/events/:eventId", async (req, res) => {
const {eventId } = req.params;
if (!mongoose.Types.ObjectId.isValid(eventId)) {
return res.status(400).json({ message: "Invalid Event ID" });
}
try {
const deletedEvent = await Event.findByIdAndDelete(eventId);
if (!deletedEvent) {
return res.status(404).json({ message: "Event not found" });
}
res.status(200).json({ message: "Event deleted successfully" });
} catch (error) {
console.error("Error deleting event:", error);
res.status(500).json({ message: "Error deleting event", error: error.message });
}
});
// PATCH /api/events/:eventId/participants
app.patch("/api/events/:eventId/participants", async (req, res) => {
const {eventId } = req.params;
if (!mongoose.Types.ObjectId.isValid(eventId)) {
return res.status(400).json({ message: "Invalid Event ID" });
}
try {
const event = await Event.findById(eventId);
if (!event) {
return res.status(404).json({ message: "Event not found" });
}
const { playerName, instrument } = req.body;
const existingParticipant = event.participants.find((p) => p.playerName === playerName);
if (existingParticipant) {
existingParticipant.instrument = instrument;
} else {
event.participants.push({ playerName, instrument });
}
const updatedEvent = await event.save();
res.status(200).json(updatedEvent);
} catch (error) {
console.error("Error adding participant:", error);
res.status(500).json({ message: "Error adding participant", error: error.message });
}
});
// PATCH /api/events/:eventId/participants/remove
app.patch("/api/events/:eventId/participants/remove", async (req, res) => {
const {eventId } = req.params;
if (!mongoose.Types.ObjectId.isValid(eventId)) {
return res.status(400).json({ message: "Invalid Event ID" });
}
try {
const event = await Event.findById(eventId);
if (!event) {
return res.status(404).json({ message: "Event not found" });
}
const { playerName } = req.body;
event.participants = event.participants.filter((p) => p.playerName !== playerName);
const updatedEvent = await event.save();
res.status(200).json(updatedEvent);
} catch (error) {
console.error("Error removing participant:", error);
res.status(500).json({ message: "Error removing participant", error: error.message });
}
});
/**
* Connection to frontend
*/
// Development environment
if (process.env.NODE_ENV === "development") {
app.use(
"*",
createProxyMiddleware({
target: "http://localhost:5173", // React development environment
changeOrigin: true,
})
);
} else {
// Serve the production build
app.use(express.static(path.join(__dirname, "./frontend/dist")));
app.get("*", function (req, res) {
res.sendFile(path.resolve(__dirname, "./frontend/dist", "index.html"));
});
}
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});