1
+ const MatchedPair = require ( '../models/matchedPairModel' ) ;
2
+
3
+ // Some database utility function for the MatchedPair Schema
4
+ async function getMatchedPairBySessionId ( sessionId ) {
5
+ try {
6
+ const matchedPair = await MatchedPair . findOne ( { sessionId : sessionId } ) ;
7
+ console . log ( `Get matched pair with session id ${ sessionId } :` , matchedPair ) ;
8
+ return matchedPair ;
9
+
10
+ } catch ( error ) {
11
+ console . error ( `Error getting matched pair with session id ${ sessionId } :` , error ) ;
12
+ }
13
+ }
14
+
15
+ async function getCurrentMatchedPair ( id ) {
16
+ try {
17
+ const matchedPair = await MatchedPair . findOne ( { $and : [ { isEnded : false } , { $or : [ { id1 : id } , { id2 : id } ] } ] } ) ;
18
+ console . log ( `Get live matched pair for ${ id } :` , matchedPair ) ;
19
+ return matchedPair ;
20
+
21
+ } catch ( error ) {
22
+ console . error ( `Error getting live matched pair for ${ id } :` , error ) ;
23
+ return null ;
24
+ }
25
+ }
26
+
27
+ async function addMatchedPair ( matchedPair ) {
28
+ try {
29
+ await matchedPair . save ( ) ;
30
+ console . log ( `Successfully added:` , matchedPair ) ;
31
+
32
+ } catch ( error ) {
33
+ console . error ( `Failed to add matched pair ${ matchedPair } :` , error ) ;
34
+ }
35
+ }
36
+
37
+ async function endSession ( sessionId ) {
38
+ try {
39
+ const filter = { sessionId : sessionId } ;
40
+ const update = { $set : { isEnded : true } } ;
41
+ await MatchedPair . updateOne ( filter , update ) ;
42
+ console . log ( `Successfully update session state for session ${ sessionId } ` ) ;
43
+
44
+ } catch ( error ) {
45
+ console . error ( `Failed to update session state for session ${ sessionId } :` , error ) ;
46
+ }
47
+ }
48
+
49
+ async function modifyMatchedPair ( sessionId , key , value ) {
50
+ try {
51
+ const filter = { sessionId : sessionId } ;
52
+ const update = {
53
+ $set : {
54
+ [ key ] : value
55
+ }
56
+ } ;
57
+ await MatchedPair . updateOne ( filter , update ) ;
58
+ console . log ( `Successfully update ${ key } state for session ${ sessionId } : ${ value } ` ) ;
59
+
60
+ } catch ( error ) {
61
+ console . error ( `Failed to update ${ key } state for session ${ sessionId } :` , error ) ;
62
+ }
63
+ }
64
+
65
+ async function deleteMatchedPair ( sessionId ) {
66
+ try {
67
+ await MatchedPair . deleteOne ( { sessionId : sessionId } ) ;
68
+ console . log ( `Successfully delete session ${ sessionId } from database.` ) ;
69
+
70
+ } catch ( error ) {
71
+ console . error ( `Failed to delete session ${ sessionId } :` , error ) ;
72
+ }
73
+ }
74
+
75
+ module . exports = {
76
+ getMatchedPairBySessionId,
77
+ getCurrentMatchedPair,
78
+ addMatchedPair,
79
+ endSession,
80
+ modifyMatchedPair,
81
+ deleteMatchedPair
82
+ } ;
0 commit comments