Skip to content
Closed
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
394 changes: 392 additions & 2 deletions shatter-backend/package-lock.json

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions shatter-backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,20 @@
"description": "",
"dependencies": {
"bcryptjs": "^3.0.3",
"cors": "^2.8.5",
"dotenv": "^17.2.3",
"express": "^5.1.0",
"mongoose": "^8.19.2",
"react-router-dom": "^7.12.0",
"socket.io": "^4.8.1",
"zod": "^4.1.12"
},
"devDependencies": {
"@eslint/js": "^9.38.0",
"@types/bcryptjs": "^2.4.6",
"@types/express": "^5.0.5",
"@types/node": "^24.9.2",
"@types/socket.io": "^3.0.1",
"eslint": "^9.38.0",
"globals": "^16.4.0",
"jiti": "^2.6.1",
Expand Down
14 changes: 14 additions & 0 deletions shatter-backend/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,30 @@
import express from 'express';
import cors from "cors";

import userRoutes from './routes/user_route'; // these routes define how to handle requests to /api/users
import authRoutes from './routes/auth_routes';
import eventRoutes from './routes/event_routes';

const app = express();

app.use(express.json());

app.use(cors({
origin: "http://localhost:3000",
credentials: true,
}));

app.use((req, _res, next) => {
req.io = app.get('socketio');
next();
});

app.get('/', (_req, res) => {
res.send('Hello');
});

app.use('/api/users', userRoutes);
app.use('/api/auth', authRoutes);
app.use('/api/events', eventRoutes);

export default app;
222 changes: 222 additions & 0 deletions shatter-backend/src/controllers/event_controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
import { Request, Response } from "express";
import { Event } from "../models/event_model";
import "../models/participant_model";

import { generateJoinCode } from "../utils/event_utils";
import { Participant } from "../models/participant_model";
import { User } from "../models/user_model";
import { Types } from "mongoose";

export async function createEvent(req: Request, res: Response) {
try {
const {
name,
description,
startDate,
endDate,
maxParticipant,
currentState,
createdBy,
} = req.body;

if (!createdBy) {
return res
.status(400)
.json({ success: false, error: "createdBy email is required" });
}

const joinCode = generateJoinCode();

const event = new Event({
name,
description,
joinCode,
startDate,
endDate,
maxParticipant,
participantIds: [],
currentState,
createdBy, // required email field
});

const savedEvent = await event.save();

res.status(201).json({ success: true, event: savedEvent });
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
}

export async function getEventByJoinCode(req: Request, res: Response) {
try {
const { joinCode } = req.params;

if (!joinCode) {
return res
.status(400)
.json({ success: false, error: "joinCode is required" });
}

// const event = await Event.findOne({ joinCode }).populate("participantIds");
const event = await Event.findOne({ joinCode });

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

res.status(200).json({
success: true,
event,
});
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
}

export async function joinEventAsUser(req: Request, res: Response) {
try {
const { name, userId } = req.body;
const { eventId } = req.params;

console.log("=== JOIN EVENT START ===");
console.log("EventId:", eventId);
console.log("UserId:", userId);
console.log("Name:", name);
console.log("req.io exists?", !!req.io);

if (!userId || !name)
return res.status(400).json({ success: false, msg: "Missing fields" });

const event = await Event.findById(eventId);
if (!event)
return res.status(404).json({ success: false, msg: "Event not found" });

if (event.participantIds.length >= event.maxParticipant)
return res.status(400).json({ success: false, msg: "Event is full" });

let participant = await Participant.findOne({
userId,
eventId,
});

if (participant) {
return res.status(409).json({ success: false, msg: "Already joined" });
}

participant = await Participant.create({
userId,
name,
eventId,
});

const participantId = participant._id as Types.ObjectId;

const eventUpdate = await Event.updateOne(
{ _id: eventId },
{ $addToSet: { participantIds: participantId } }
);

// If nothing changed → already joined
if (eventUpdate.modifiedCount === 0) {
return res
.status(400)
.json({ success: false, msg: "Already joined this event" });
}

// 2. Add event to user history
await User.updateOne(
{ _id: userId },
{ $addToSet: { eventHistoryIds: eventId } }
);

console.log("=== EMITTING SOCKET EVENT ===");
console.log("Room (eventId):", eventId);
console.log("Participant data:", { participantId, name });

if (!req.io) {
console.error("ERROR: req.io is undefined!");
} else {
const room = req.io.to(eventId);
console.log("Room object:", room);

room.emit("participant-joined", {
participantId,
name,
});

console.log("Socket event emitted successfully");
}

return res.json({
success: true,
participant,
});
} catch (e) {
console.error("JOIN EVENT ERROR:", e);
return res.status(500).json({ success: false, msg: "Internal error" });
}
}

export async function joinEventAsGuest(req: Request, res: Response) {
try {
const { name } = req.body;
const { eventId } = req.params;

if (!name) {
return res
.status(400)
.json({ success: false, msg: "Missing guest name" });
}

const event = await Event.findById(eventId);
if (!event) {
return res.status(404).json({ success: false, msg: "Event not found" });
}

if (event.participantIds.length >= event.maxParticipant) {
return res.status(400).json({ success: false, msg: "Event is full" });
}

// Create guest participant (userId is null)
const participant = await Participant.create({
userId: null,
name,
eventId,
});

const participantId = participant._id as Types.ObjectId;

// Add participant to event
await Event.updateOne(
{ _id: eventId },
{ $addToSet: { participantIds: participantId } }
);

// Emit socket
console.log("=== EMITTING SOCKET EVENT ===");
console.log("Room (eventId):", eventId);
console.log("Participant data:", { participantId, name });

if (!req.io) {
console.error("ERROR: req.io is undefined!");
} else {
const room = req.io.to(eventId);
console.log("Room object:", room);

room.emit("participant-joined", {
participantId,
name,
});

console.log("Socket event emitted successfully");
}

return res.json({
success: true,
participant,
});
} catch (err) {
console.error("JOIN GUEST ERROR:", err);
return res.status(500).json({ success: false, msg: "Internal error" });
}
}
54 changes: 54 additions & 0 deletions shatter-backend/src/models/event_model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import mongoose, { Schema, model, Document, Types } from "mongoose";
import { User } from "../models/user_model";

import { IParticipant } from "./participant_model";

export interface IEvent extends Document {
name: string;
description: string;
joinCode: string;
startDate: Date;
endDate: Date;
maxParticipant: number;
participantIds: Schema.Types.ObjectId[];
currentState: string;
createdBy: string;
}

const EventSchema = new Schema<IEvent>(
{
name: { type: String, required: true },
description: { type: String, required: true },
joinCode: { type: String, required: true, unique: true },
startDate: { type: Date, required: true },
endDate: { type: Date, required: true },
maxParticipant: { type: Number, required: true },
participantIds: [{ type: Schema.Types.ObjectId, ref: "Participant" }],
currentState: { type: String, required: true },
createdBy: {
type: String,
required: true,
validate: {
validator: async function (email: string) {
const user = await User.findOne({ email });
return !!user;
},
message: "User with this email does not exist",
},
},
},
{
timestamps: true,
}
);

// Optional validation: ensure endDate is after startDate
EventSchema.pre("save", function (next) {
if (this.endDate <= this.startDate) {
next(new Error("endDate must be after startDate"));
} else {
next();
}
});

export const Event = model<IEvent>("Event", EventSchema);
32 changes: 32 additions & 0 deletions shatter-backend/src/models/participant_model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Schema, model, Document } from "mongoose";

export interface IParticipant extends Document {
userId: Schema.Types.ObjectId | null;
name: string;
eventId: Schema.Types.ObjectId;
}

const ParticipantSchema = new Schema<IParticipant>({
userId: {
type: Schema.Types.ObjectId,
ref: "User",
default: null,
},

name: {
type: String,
ref: "User Name",
required: true,
},

eventId: {
type: Schema.Types.ObjectId,
ref: "Event",
required: true,
},
});

export const Participant = model<IParticipant>(
"Participant",
ParticipantSchema
);
Loading
Loading