1
- export async function create_room ( req , res ) {
2
- // this function is to create a connection between two users
3
- // the connection is store in mongodb
1
+ import { createRoom , get_roomID , heartbeat , get_all_rooms } from '../model/repository.js' ;
2
+ import crypto from 'crypto' ;
4
3
4
+ // Create a room between two users
5
+ export async function create_room ( req , res ) {
5
6
const { user1, user2 } = req . body ;
6
7
7
- }
8
+ if ( ! user1 || ! user2 ) {
9
+ return res . status ( 400 ) . json ( { error : 'Both user1 and user2 are required' } ) ;
10
+ }
11
+
12
+ // Generate a unique room ID by hashing the two user IDs
13
+ const roomId = crypto . createHash ( 'sha256' ) . update ( user1 + user2 ) . digest ( 'hex' ) ;
14
+ const room = await createRoom ( user1 , user2 , roomId ) ;
15
+
16
+ if ( room ) {
17
+ res . status ( 201 ) . json ( room ) ;
18
+ } else {
19
+ res . status ( 500 ) . json ( { error : 'Failed to create room' } ) ;
20
+ }
21
+ }
22
+
23
+ // Get room ID by user
24
+ export async function get_room_by_user ( req , res ) {
25
+ const { user } = req . params ;
26
+
27
+ if ( ! user ) {
28
+ return res . status ( 400 ) . json ( { error : 'User is required' } ) ;
29
+ }
30
+
31
+ const room = await get_roomID ( user ) ;
32
+
33
+ if ( room ) {
34
+ res . status ( 200 ) . json ( room ) ;
35
+ } else {
36
+ res . status ( 404 ) . json ( { error : `Room not found for user: ${ user } ` } ) ;
37
+ }
38
+ }
39
+
40
+ // Update heartbeat for a room
41
+ export async function update_heartbeat ( req , res ) {
42
+ const { roomId } = req . params ;
43
+
44
+ if ( ! roomId ) {
45
+ return res . status ( 400 ) . json ( { error : 'Room ID is required' } ) ;
46
+ }
47
+
48
+ const updatedRoom = await heartbeat ( roomId ) ;
49
+
50
+ if ( updatedRoom ) {
51
+ res . status ( 200 ) . json ( updatedRoom ) ;
52
+ } else {
53
+ res . status ( 404 ) . json ( { error : `Room with ID ${ roomId } not found` } ) ;
54
+ }
55
+ }
56
+
57
+ // Get all rooms
58
+ export async function get_all_rooms_controller ( req , res ) {
59
+ const rooms = await get_all_rooms ( ) ;
60
+
61
+ if ( rooms ) {
62
+ res . status ( 200 ) . json ( rooms ) ;
63
+ } else {
64
+ res . status ( 500 ) . json ( { error : 'Failed to retrieve rooms' } ) ;
65
+ }
66
+ }
0 commit comments