Skip to content

Commit 3e7996a

Browse files
committed
working
1 parent 5630482 commit 3e7996a

File tree

11 files changed

+71
-61
lines changed

11 files changed

+71
-61
lines changed

backend/matching/.env.docker

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,9 @@ EXPRESS_PORT=9004
55
MATCHING_DB_HOSTNAME=host.docker.internal
66
MATCHING_DB_PORT=6379
77

8+
USER_SERVER_ENDPOINT=http://localhost:9001
9+
QUESTION_SERVER_ENDPOINT=http://localhost:9002
10+
COLLAB_SERVICE_ENDPOINT=http://localhost:9003
11+
812
# MATCHING_DB_USERNAME=peerprep-match-express
913
# MATCHING_DB_PASSWORD=G7jBgyz9wGAFQ5La

backend/matching/.env.local

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ EXPRESS_PORT=9004
55
MATCHING_DB_HOSTNAME="localhost"
66
MATCHING_DB_PORT=6379
77

8-
USER_SERVER_ENDPOINT="http://localhost:9003"
8+
USER_SERVER_ENDPOINT="http://localhost:9001"
99
QUESTION_SERVER_ENDPOINT="http://localhost:9002"
10-
COLLAB_SERVER_ENDPOINT="http://localhost:9004"
10+
COLLAB_SERVER_ENDPOINT="http://localhost:9003"
1111

1212

1313
# MATCHING_DB_USERNAME="peerprep-match-express"

backend/matching/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
docker build \
88
-t match-express-local \
99
--build-arg port=9004 \
10+
--build-arg USER_SERVER_ENDPOINT=http://host.docker.internal:9001 \
11+
--build-arg QUESTION_SERVER_ENDPOINT=http://host.docker.internal:9002 \
12+
--build-arg COLLAB_SERVICE_ENDPOINT=http://host.docker.internal:9003 \
1013
-f express.Dockerfile .
1114
```
1215
2. Run this command, from the root folder:

backend/matching/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
"description": "",
2020
"dependencies": {
2121
"async": "^3.2.6",
22+
"axios": "^1.7.7",
2223
"cors": "^2.8.5",
2324
"dotenv": "^16.4.5",
2425
"env-cmd": "^10.1.0",

backend/matching/src/services/get-match-items.ts

Lines changed: 37 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@ interface IGetRandomQuestionPayload {
77
topic?: string;
88
}
99

10+
11+
interface IServiceResponse<T> {
12+
success: boolean;
13+
data?: T;
14+
error?: { message: string };
15+
}
16+
1017
interface IQuestion {
1118
id: number;
1219
title: string;
@@ -15,25 +22,19 @@ interface IQuestion {
1522
topic: string[];
1623
}
1724

18-
interface IServiceResponse<T> {
19-
success: boolean;
20-
data?: T;
21-
error?: { message: string };
22-
}
23-
2425
interface IMatchItemsResponse {
25-
roomId: string;
26-
questionId: number;
27-
question: IQuestion;
26+
roomName: string;
27+
questionId: number;
28+
question: IQuestion;
2829
}
2930

3031
export const getMatchItems = async (
31-
searchIdentifier: IMatchType,
32-
topic?: string,
33-
difficulty?: string,
34-
userId1?: string,
35-
userId2?: string
36-
): Promise<IServiceResponse<IMatchItemsResponse>> => {
32+
searchIdentifier: IMatchType,
33+
topic?: string,
34+
difficulty?: string,
35+
userId1?: string,
36+
userId2?: string
37+
): Promise<IMatchItemsResponse | undefined> => {
3738
const userEndpoint = `${process.env.USER_SERVER_ENDPOINT}`;
3839
const questionEndpoint = `${process.env.QUESTION_SERVER_ENDPOINT}`;
3940
const collabServerEndpoint = `${process.env.COLLAB_SERVER_ENDPOINT}`;
@@ -68,11 +69,11 @@ export const getMatchItems = async (
6869

6970
// Query the question endpoint using the /random endpoint
7071
const questionResponse = await axios.post<IServiceResponse<{ question: IQuestion }>>(
71-
`${questionEndpoint}/random`,
72+
`${questionEndpoint}/questions/random`,
7273
payload
7374
);
7475

75-
if (!questionResponse.data.success || !questionResponse.data.data?.question) {
76+
if (questionResponse.status !== 200 || !questionResponse.data.data) {
7677
throw new Error(questionResponse.data.error?.message || 'Failed to get a random question');
7778
}
7879

@@ -85,56 +86,48 @@ export const getMatchItems = async (
8586
]);
8687

8788
// Query the collab server for the room ID
88-
const roomResponse = await axios.get<IServiceResponse<{ roomId: string }>>(
89-
`${collabServerEndpoint}/rooms`,
89+
const roomResponse = await axios.get<{ roomName: string }>(
90+
`${collabServerEndpoint}/room`,
9091
{
9192
params: {
92-
userId1,
93-
userId2,
94-
questionId: questionId.toString(),
93+
userid1: userId1,
94+
userid2: userId2,
95+
questionid: questionId.toString(),
9596
}
9697
}
97-
);
98-
99-
if (!roomResponse.data.success || !roomResponse.data.data?.roomId) {
100-
throw new Error(roomResponse.data.error?.message || 'Failed to create room');
98+
);
99+
if (roomResponse.status !== 200 || !roomResponse.data?.roomName) {
100+
throw new Error('Failed to create room');
101101
}
102102

103+
console.log("Succesfully got match items");
103104
return {
104-
success: true,
105-
data: {
106-
roomId: roomResponse.data.data.roomId,
105+
roomName: roomResponse.data.roomName,
107106
questionId: questionId,
108107
question: questionResponse.data.data.question,
109108
}
110-
};
111109
} catch (error) {
112110
console.error('Error in getMatchItems:', error);
113-
return {
114-
success: false,
115-
error: {
116-
message: error instanceof Error ? error.message : 'An unknown error occurred',
117-
}
118-
};
119-
}
120111
};
112+
}
121113

122114
async function fetchAttemptedQuestions(userEndpoint: string, userId: string): Promise<number[]> {
123-
const response = await axios.get<IServiceResponse<{ attemptedQuestions: number[] }>>(
115+
const response = await axios.get<number[]>(
124116
`${userEndpoint}/user/${userId}/attempted-questions`
125117
);
126-
if (!response.data.success || !response.data.data?.attemptedQuestions) {
118+
if (response.status !== 200 || !response.data) {
127119
throw new Error(`Failed to fetch attempted questions for user ${userId}`);
128120
}
129-
return response.data.data.attemptedQuestions;
121+
return response.data || []
130122
}
131123

132124
async function updateAttemptedQuestions(userEndpoint: string, userId: string, questionId: number): Promise<void> {
133-
const response = await axios.post<IServiceResponse<{ message: string }>>(
134-
`${userEndpoint}/user/${userId}/attempted-question`,
125+
const response = await axios.post<unknown>(
126+
`${userEndpoint}/user/${userId}/attempt-question`,
135127
{ questionId }
136128
);
137-
if (!response.data.success) {
138-
throw new Error(`Failed to update attempted questions for user ${userId}`);
129+
if (response.status !== 200 || !response.data) {
130+
throw new Error(`Failed to fetch attempted questions for user ${userId}`);
139131
}
132+
return;
140133
}

backend/matching/src/workers/matcher.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ async function processMatch(
7474
]);
7575

7676
// Notify both sockets
77-
const { ...matchItems } = getMatchItems(searchIdentifier, topic, difficulty, requestorUserId, matchedUserId);
77+
const { ...matchItems } = await getMatchItems(searchIdentifier, topic, difficulty, requestorUserId, matchedUserId);
78+
logger.info(`matchItems: ${JSON.stringify(matchItems)}`);
79+
7880
sendNotif([requestorSocketPort, matchedSocketPort], MATCH_SVC_EVENT.SUCCESS, matchItems);
7981
sendNotif([requestorSocketPort, matchedSocketPort], MATCH_SVC_EVENT.DISCONNECT);
8082

@@ -89,6 +91,7 @@ async function processMatch(
8991

9092
async function match() {
9193
const redisClient = await connectClient(client);
94+
9295
const stream = await redisClient.xReadGroup(
9396
STREAM_GROUP,
9497
STREAM_WORKER,

backend/user/src/routes/auth.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import express from 'express';
22

33
import { checkEmailValid, checkUsernameValid, login, logout, register } from '@/controllers/auth';
44
import { limiter } from '@/lib/ratelimit';
5-
import { getAttemptedQuestions, addAttemptedQuestion } from '@/controllers/questions';
65

76
const router = express.Router();
87

@@ -12,8 +11,7 @@ router.post('/register', register);
1211
router.post('/username-valid', checkUsernameValid);
1312
router.post('/email-valid', checkEmailValid);
1413

15-
router.post('/attempted-questions', getAttemptedQuestions)
16-
router.post('/attempt-question', addAttemptedQuestion)
14+
1715
router.use(limiter);
1816

1917
export default router;

backend/user/src/routes/user.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import express from 'express';
2+
3+
import { getAttemptedQuestions, addAttemptedQuestion } from '@/controllers/questions';
4+
5+
6+
const router = express.Router();
7+
8+
router.get('/:userId/attempted-questions/', getAttemptedQuestions)
9+
router.post('/:userId/attempt-question', addAttemptedQuestion)
10+
11+
export default router;

backend/user/src/server.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { dbConfig, UI_HOST } from '@/config';
1212
import { db } from '@/lib/db';
1313
import { logger } from '@/lib/utils';
1414
import authRoutes from '@/routes/auth';
15+
import userRoutes from '@/routes/user';
1516
import authCheckRoutes from '@/routes/auth-check';
1617

1718
const app = express();
@@ -28,6 +29,7 @@ app.use(
2829

2930
app.use('/auth', authRoutes);
3031
app.use('/auth-check', authCheckRoutes);
32+
app.use('/user', userRoutes)
3133

3234
// Health Check for Docker
3335
app.get('/health', (_req, res) => res.status(StatusCodes.OK).send('OK'));

backend/user/src/services/questions/index.ts

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ interface IAddAttemptedQuestionResponse {
2424
const user = await db
2525
.select({ attemptedQuestions: users.attemptedQuestions })
2626
.from(users)
27-
.where(eq(users.id, userId))
27+
.where(eq(users.username, userId))
2828
.limit(1);
2929

3030
if (user.length === 0) {
@@ -49,14 +49,7 @@ interface IAddAttemptedQuestionResponse {
4949
.set({
5050
attemptedQuestions: sql`array_append(${users.attemptedQuestions}, ${questionId})`,
5151
})
52-
.where(eq(users.id, userId));
53-
54-
if (result.length === 0) {
55-
return {
56-
code: StatusCodes.NOT_FOUND,
57-
error: new Error('Failed to update user'),
58-
};
59-
}
52+
.where(eq(users.username, userId))
6053

6154
return {
6255
code: StatusCodes.OK,
@@ -76,7 +69,7 @@ export const getAttemptedQuestionsService = async (userId: string): Promise<IGet
7669
const result = await db
7770
.select({ attemptedQuestions: users.attemptedQuestions })
7871
.from(users)
79-
.where(eq(users.id, userId))
72+
.where(eq(users.username, userId))
8073
.limit(1);
8174

8275
if (result.length === 0) {

0 commit comments

Comments
 (0)