Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions shatter-backend/docs/API_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
- [POST `/api/events/:eventId/leave`](#post-apieventseventidleave)
- [DELETE `/api/events/:eventId`](#delete-apieventseventid)
- [GET `/api/events/createdEvents/user/:userId`](#get-apieventscreatedeventsuseruserid)
- [PUT `/api/events/:eventId`](#put-apieventseventid)
- [Bingo (`/api/bingo`)](#bingo-apibingo)
- [POST `/api/bingo/createBingo`](#post-apibingocreatebingo)
- [GET `/api/bingo/getBingo/:eventId`](#get-apibingogetbingoeventid)
Expand Down Expand Up @@ -981,6 +982,89 @@ Get all events created by a specific user.
| Status | Error |
|--------|-------|
| 404 | `"No events found for this user"` |
---
### PUT `/api/events/:eventId`

Update an existing event's basic information (host only). Only the fields provided in the request body will be updated. To change event status, use `PUT /api/events/:eventId/status` instead.

- **Auth:** Protected (Bearer Token required)

---

**URL Params:**

| Param | Type | Required |
|-----------|----------|----------|
| `eventId` | ObjectId | Yes |

---

**Request Body (all fields optional):**

| Field | Type | Description |
|------------------|----------|------------------------------------------|
| `name` | string | Updated event name (cannot be empty) |
| `description` | string | Updated event description (cannot be empty) |
| `startDate` | Date | Updated start date (ISO string) |
| `endDate` | Date | Updated end date (ISO string) |
| `maxParticipant` | number | Updated max participants (positive integer, >= current count) |
| `gameType` | string | `"Name Bingo"` |
| `eventImg` | string | URL of event image |

---

**Success Response (200):**

```json
{
"success": true,
"message": "Event updated successfully",
"data": {
"_id": "665a...",
"name": "Updated Event Name",
"description": "New description",
"startDate": "2026-05-01T10:00:00.000Z",
"endDate": "2026-05-02T10:00:00.000Z",
"maxParticipant": 50,
"currentState": "Upcoming",
"gameType": "Name Bingo",
"createdBy": "664f..."
}
}
```

---

**Error Responses:**

| Status | Error |
|--------|-------|
| 400 | `"Missing eventId"` |
| 400 | `"Invalid eventId"` |
| 400 | `"No fields provided to update"` |
| 400 | `"Name must be a non-empty string"` |
| 400 | `"Description must be a non-empty string"` |
| 400 | `"Invalid startDate"` |
| 400 | `"Invalid endDate"` |
| 400 | `"endDate must be after startDate"` |
| 400 | `"maxParticipant must be a positive integer"` |
| 400 | `"maxParticipant cannot be less than the current number of participants ({count})"` |
| 400 | `"Invalid gameType. Must be one of: Name Bingo"` |
| 400 | `"eventImg must be a string"` |
| 400 | `"Cannot update a completed event"` |
| 401 | `"Unauthorized: missing authenticated user"` |
| 403 | `"Only the event creator can update this event"` |
| 404 | `"Event not found"` |

---

**Notes:**

- Only the event creator (`createdBy`) can update the event.
- Fields not included in the request body will remain unchanged.
- `currentState` cannot be changed through this endpoint — use `PUT /api/events/:eventId/status`.
- `startDate` and `endDate` must be valid ISO date strings, and `endDate` must be after `startDate`.
- `maxParticipant` cannot be set below the current number of participants in the event.

---

Expand Down
215 changes: 214 additions & 1 deletion shatter-backend/src/controllers/event_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -683,4 +683,217 @@ export async function deleteEvent(req: Request, res: Response) {
console.error("DELETE EVENT ERROR:", err);
return res.status(500).json({ success: false, error: err.message });
}
}
}


/**
* PUT /api/events/:eventId
* Update an event's basic information (host only).
* Does NOT allow changing currentState — use PUT /:eventId/status for that.
*
* @param req.params.eventId - Event ID to update (required)
* @param req.user.userId - Authenticated user ID (from access token)
*
* @param req.body.name - Updated event name (optional)
* @param req.body.description - Updated event description (optional)
* @param req.body.startDate - Updated event start date (optional)
* @param req.body.endDate - Updated event end date (optional)
* @param req.body.maxParticipant - Updated maximum number of participants (optional)
* @param req.body.gameType - Updated game type of the event (optional)
* @param req.body.eventImg - Updated event image URL (optional)
*
* @returns 200 on success
* @returns 400 if event is completed or validation fails
* @returns 403 if user is not the host
* @returns 404 if event not found
*/
type UpdateEventBody = {
name?: string;
description?: string;
startDate?: string | Date;
endDate?: string | Date;
maxParticipant?: number;
gameType?: "Name Bingo";
eventImg?: string;
};

export async function updateEvent(req: Request<{ eventId: string }, {}, UpdateEventBody>, res: Response) {
try {
const { eventId } = req.params;
const userId = req.user?.userId;

if (!eventId) {
return res.status(400).json({
success: false,
error: "Missing eventId",
});
}

if (!userId) {
return res.status(401).json({
success: false,
error: "Unauthorized: missing authenticated user",
});
}

if (!Types.ObjectId.isValid(eventId)) {
return res.status(400).json({
success: false,
error: "Invalid eventId",
});
}

const event = await Event.findById(eventId);

if (!event) {
return res.status(404).json({
success: false,
error: "Event not found",
});
}

// Verify authenticated user is the creator/host
if (event.createdBy.toString() !== userId.toString()) {
return res.status(403).json({
success: false,
error: "Only the event creator can update this event",
});
}

if (event.currentState === "Completed") {
return res.status(400).json({
success: false,
error: "Cannot update a completed event",
});
}

const {
name,
description,
startDate,
endDate,
maxParticipant,
gameType,
eventImg,
} = req.body;

const updateData: Partial<{
name: string;
description: string;
startDate: Date;
endDate: Date;
maxParticipant: number;
gameType: "Name Bingo";
eventImg: string;
}> = {};

// Validate and set name
if (name !== undefined) {
if (typeof name !== "string" || !name.trim()) {
return res.status(400).json({ success: false, error: "Name must be a non-empty string" });
}
updateData.name = name;
}

// Validate and set description
if (description !== undefined) {
if (typeof description !== "string" || !description.trim()) {
return res.status(400).json({ success: false, error: "Description must be a non-empty string" });
}
updateData.description = description;
}

// Validate and set startDate
if (startDate !== undefined) {
if (startDate === null || typeof startDate === "boolean") {
return res.status(400).json({ success: false, error: "Invalid startDate" });
}
const parsed = new Date(startDate);
if (isNaN(parsed.getTime())) {
return res.status(400).json({ success: false, error: "Invalid startDate" });
}
updateData.startDate = parsed;
}

// Validate and set endDate
if (endDate !== undefined) {
if (endDate === null || typeof endDate === "boolean") {
return res.status(400).json({ success: false, error: "Invalid endDate" });
}
const parsed = new Date(endDate);
if (isNaN(parsed.getTime())) {
return res.status(400).json({ success: false, error: "Invalid endDate" });
}
updateData.endDate = parsed;
}

// Validate and set maxParticipant
if (maxParticipant !== undefined) {
if (maxParticipant === null || !Number.isInteger(maxParticipant) || maxParticipant <= 0) {
return res.status(400).json({ success: false, error: "maxParticipant must be a positive integer" });
}
if (maxParticipant < event.participantIds.length) {
return res.status(400).json({
success: false,
error: `maxParticipant cannot be less than the current number of participants (${event.participantIds.length})`,
});
}
updateData.maxParticipant = maxParticipant;
}

// Validate and set gameType
if (gameType !== undefined) {
const validGameTypes = ["Name Bingo"];
if (typeof gameType !== "string" || !validGameTypes.includes(gameType)) {
return res.status(400).json({ success: false, error: `Invalid gameType. Must be one of: ${validGameTypes.join(", ")}` });
}
updateData.gameType = gameType;
}

if (eventImg !== undefined) {
if (typeof eventImg !== "string") {
return res.status(400).json({ success: false, error: "eventImg must be a string" });
}
updateData.eventImg = eventImg;
}

if (Object.keys(updateData).length === 0) {
return res.status(400).json({
success: false,
error: "No fields provided to update",
});
}

// Validate date ordering (compare updated dates against existing ones)
const finalStartDate = updateData.startDate ?? event.startDate;
const finalEndDate = updateData.endDate ?? event.endDate;

if (finalEndDate <= finalStartDate) {
return res.status(400).json({
success: false,
error: "endDate must be after startDate",
});
}

const updatedEvent = await Event.findByIdAndUpdate(
eventId,
{ $set: updateData },
{
new: true,
runValidators: true,
}
);

return res.status(200).json({
success: true,
message: "Event updated successfully",
data: updatedEvent,
});
} catch (err: any) {
console.error("UPDATE EVENT ERROR:", err);
return res.status(500).json({
success: false,
error: err.message || "Internal server error",
});
}
}
6 changes: 3 additions & 3 deletions shatter-backend/src/routes/event_routes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Router } from 'express';
import { createEvent, getEventByJoinCode, getEventById, joinEventAsUser, joinEventAsGuest, getEventsByUserId, updateEventStatus, leaveEvent, deleteEvent } from '../controllers/event_controller.js';
import { createEvent, getEventByJoinCode, getEventById, joinEventAsUser, joinEventAsGuest, getEventsByUserId, updateEventStatus, leaveEvent, deleteEvent, updateEvent } from '../controllers/event_controller.js';
import { authMiddleware } from '../middleware/auth_middleware.js';

const router = Router();
Expand All @@ -14,6 +14,6 @@ router.post("/:eventId/join/guest", joinEventAsGuest);
router.post("/:eventId/leave", authMiddleware, leaveEvent);
router.delete("/:eventId", authMiddleware, deleteEvent);
router.get("/createdEvents/user/:userId", authMiddleware, getEventsByUserId);
router.put("/:eventId", authMiddleware, updateEvent);


export default router;
export default router;
Loading