Skip to content

Commit f2a09ae

Browse files
authored
Merge pull request #46 from CS3219-AY2324S1/refactor-backend
Refactor backend
2 parents 844fcb3 + 57643cb commit f2a09ae

File tree

16 files changed

+2204
-71
lines changed

16 files changed

+2204
-71
lines changed

backend/package-lock.json

Lines changed: 1883 additions & 48 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

backend/package.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@
1414
"dotenv": "^16.3.1",
1515
"express": "~4.16.1",
1616
"firebase": "^10.4.0",
17-
"http-errors": "~1.6.3"
17+
"firebase-admin": "^11.11.0",
18+
"http": "^0.0.1-security",
19+
"http-errors": "~1.6.3",
20+
"socket.io": "^4.7.2"
1821
},
1922
"devDependencies": {
2023
"@types/express": "^4.17.18",

backend/src/index.ts

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,51 @@ import {
66
handleSignUp,
77
} from "./auth/auth.controller";
88
import { handleCreateUser, handleGetUser } from "./user/user.controller";
9+
import { initializeApp } from 'firebase/app';
10+
import { getFirestore } from 'firebase/firestore';
11+
import { firebaseConfig } from "./firebase/firebase.config";
12+
import { initializeMatchingService } from './matching/matching.service'; // Import the matching service function
13+
import { Socket, Server } from 'socket.io';
14+
import { Server as ServerHttp } from 'http';
15+
import { handleCreateUser, handleGetUser, handleUpdateUser } from "./user/user.controller";
916
const app = express();
1017
const port = 3001;
11-
1218
app.use(cors());
1319
app.use(express.json());
1420

21+
const httpServer = new ServerHttp(app);
22+
const io = new Server(httpServer, {
23+
cors: {
24+
origin: '*',
25+
},
26+
});
27+
1528
app.get("/", (req, res) => {
1629
res.send("Hello World!");
1730
});
1831

32+
// Initialize Firebase Firestore and other configurations here
33+
initializeApp(firebaseConfig);
34+
const db = getFirestore();
35+
1936
app.post("/signup", handleSignUp);
2037
app.post("/login", handleLogin);
2138
app.delete("/logout", handleLogout);
2239
app.post("/user", handleCreateUser);
2340
app.get("/user", handleGetUser);
41+
app.put("/user", handleUpdateUser);
42+
43+
//Socket logic
44+
// Maintain an array to store active users seeking a match
45+
const activeUsers: { socket: Socket; preferences: any }[] = [];
46+
47+
// Initialize the matching service by passing the io object
48+
initializeMatchingService(io);
49+
50+
// httpServer.listen(socketPort, () => {
51+
// console.log(`socket listening on port ${socketPort}`);
52+
// });
2453

25-
app.listen(port, () => {
54+
httpServer.listen(port, () => {
2655
console.log(`Peerprep listening on port ${port}`);
2756
});
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { Server, Socket } from 'socket.io';
2+
3+
// Your existing matching service logic
4+
export function initializeMatchingService(io: Server) {
5+
// Maintain an array to store active users seeking a match
6+
const activeUsers: { socket: Socket; preferences: any }[] = [];
7+
8+
io.on('connection', (socket: Socket) => {
9+
console.log('A user connected');
10+
11+
socket.on('startMatching', (preferences: any) => {
12+
// Add the user to the list of active users with their preferences
13+
activeUsers.push({ socket, preferences });
14+
15+
// Attempt to find a match for the user
16+
tryMatchForUser(socket, preferences);
17+
});
18+
19+
socket.on('disconnect', () => {
20+
console.log('A user disconnected');
21+
22+
// Remove the user from the list of active users when they disconnect
23+
removeUserFromActiveList(socket);
24+
});
25+
26+
// Other event handlers as needed
27+
});
28+
29+
function tryMatchForUser(socket: Socket, preferences: any) {
30+
const { difficulty, category } = preferences;
31+
32+
// Iterate through active users to find a match
33+
const matchedUser = activeUsers.find((user) => {
34+
return (
35+
user.socket !== socket && // Exclude the current user from matching with themselves
36+
user.preferences.difficulty === difficulty &&
37+
user.preferences.category === category
38+
);
39+
});
40+
41+
if (matchedUser) {
42+
// Remove both users from the active list
43+
removeUserFromActiveList(socket);
44+
removeUserFromActiveList(matchedUser.socket);
45+
46+
// Emit "matchFound" to both users
47+
socket.emit('matchFound', matchedUser.preferences);
48+
matchedUser.socket.emit('matchFound', preferences);
49+
} else {
50+
// Handle the case when no match is found for the user
51+
// You can emit a "noMatchFound" event or handle it differently
52+
}
53+
}
54+
55+
function removeUserFromActiveList(socket: Socket) {
56+
// Remove the user from the list of active users by socket ID
57+
const index = activeUsers.findIndex((user) => user.socket === socket);
58+
if (index !== -1) {
59+
activeUsers.splice(index, 1);
60+
}
61+
}
62+
}

backend/src/user/user.controller.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Request, Response } from "express";
2-
import { createUser, getUser } from "./user.service";
2+
import { createUser, getUser, updateUser } from "./user.service";
33

44
export async function handleCreateUser(req: Request, res: Response) {
55
try {
@@ -29,3 +29,19 @@ export async function handleGetUser(req: Request, res: Response) {
2929
res.status(500).send(error);
3030
}
3131
}
32+
33+
export async function handleUpdateUser(req: Request, res: Response) {
34+
try {
35+
const email = req.body.params.email;
36+
if (typeof email === "string") {
37+
console.log(`updating user ${email}`);
38+
const user = await updateUser(email, req.body.params)
39+
res.status(200).send(user);
40+
} else {
41+
res.status(500).send("no params");
42+
}
43+
} catch (error) {
44+
console.error(error);
45+
res.status(500).send(error);
46+
}
47+
}

backend/src/user/user.service.ts

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { initializeApp } from "firebase/app";
2-
import { doc, getDoc, getFirestore, setDoc } from "firebase/firestore";
2+
import { doc, getDoc, getFirestore, setDoc, updateDoc } from "firebase/firestore";
33
import { firebaseConfig } from "../firebase/firebase.config";
44

55
initializeApp(firebaseConfig);
@@ -18,11 +18,17 @@ export async function createUser(email: string): Promise<User> {
1818
try {
1919
await setDoc(doc(db, "users", email), {
2020
email: email,
21+
name: "-",
22+
year: "-",
23+
major: "-",
2124
role: "user",
2225
completed: 0,
2326
});
2427
return Promise.resolve({
2528
email: email,
29+
name: "-",
30+
year: "-",
31+
major: "-",
2632
role: "user",
2733
completed: 0,
2834
});
@@ -50,3 +56,29 @@ export async function getUser(email: string): Promise<User> {
5056
return Promise.reject(error);
5157
}
5258
}
59+
60+
export async function updateUser(email: string, params: any): Promise<User> {
61+
try {
62+
const document = doc(db, "users", email);
63+
await updateDoc(document, {
64+
name: params.name,
65+
year: params.year,
66+
major: params.major
67+
})
68+
const data = await getDoc(doc(db, "users", email));
69+
const user = data.data();
70+
if (user) {
71+
return Promise.resolve({
72+
email: email,
73+
name: user.name ? user.name : undefined,
74+
year: user.year ? user.year : undefined,
75+
major: user.major ? user.major : undefined,
76+
role: user.role,
77+
completed: user.completed,
78+
});
79+
}
80+
return Promise.reject("no such user");
81+
} catch (error) {
82+
return Promise.reject(error);
83+
}
84+
}

backend/tsconfig.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,4 @@
1010
},
1111
"include": ["./**/*.ts"],
1212
"exclue": ["node_modules"]
13-
}
13+
}

frontend/package-lock.json

Lines changed: 80 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

frontend/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
"react-router-dom": "^6.16.0",
2424
"react-scripts": "5.0.1",
2525
"react-simple-code-editor": "^0.13.1",
26+
"socket.io-client": "^4.7.2",
2627
"typescript": "^4.9.5",
2728
"web-vitals": "^2.1.4"
2829
},

frontend/src/api/user/data.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
import {httpClient} from "../axios/config";
2-
import { UserModel } from "./model";
2+
import { UserModel, Values } from "./model";
3+
34

45
export const createUser = (email: string) =>
56
httpClient.post<UserModel>("/user", { email: email });
67

78
export const getUser = (email: string) =>
89
httpClient.get<UserModel>("/user", { params: { email: email } });
10+
11+
export const updateUser = (params: Values) =>
12+
httpClient.put<UserModel>("/user", { params });

0 commit comments

Comments
 (0)