1+ const express = require ( 'express' ) ;
2+ const firebase = require ( '../firebase/firebase.js' ) ;
3+ const rootRef = firebase . database ( ) . ref ( ) ;
4+ const router = express . Router ( ) ;
5+
6+
7+ //--------------------------------------------------------POSTS
8+
9+ router . post (
10+ '/addMessage' ,
11+ ( req , res ) => {
12+
13+ const messageKey = rootRef . push ( null ) . key ;
14+
15+ // Deconstruct Request Body
16+ const {
17+ uid, // User ID (Sender)
18+ pid, // Participant ID (Receiver)
19+ message,
20+ name,
21+ participant,
22+ date
23+ } = req . body ;
24+
25+ cid = [ uid , pid ] . sort ( ) . join ( '_' ) ; // Conversation ID - Combination of Sender's and Receiver's UIDs.
26+
27+ // Check for Missing Required Information
28+ if ( ! pid || ! uid || ! message || ! name || ! participant || ! date ) {
29+ return res . status ( 400 ) . json ( { "errorMessage" :"Please send a message, date, and the names and ids of both participants." } )
30+ }
31+
32+ // Construct New Message Object
33+ let newMessage = {
34+ date,
35+ message,
36+ name,
37+ }
38+
39+ // Construct Object to Add to User's Conversation Lookup (Sender)
40+ let newUserLookup = {
41+ lastMessage : newMessage ,
42+ participant : {
43+ name : participant ,
44+ uid : pid
45+ }
46+ }
47+
48+ // Construct Object to Add to Participant's Conversation Lookup (Receiver)
49+ let newParticipantLookup = {
50+ lastMessage : newMessage ,
51+ participant : {
52+ name,
53+ uid
54+ }
55+ }
56+
57+ // Create Object to Update Firebase
58+ let updateObject = { } ;
59+
60+ // Set Up New Message to be Added to Conversations and Conversation Lookup
61+ updateObject [ `conversations/${ cid } /${ messageKey } ` ] = newMessage ;
62+ updateObject [ `conversationLookup/${ uid } /${ cid } ` ] = newUserLookup ; // Lookup for Sender
63+ updateObject [ `conversationLookup/${ pid } /${ cid } ` ] = newParticipantLookup ; // Lookup for Receiver
64+
65+
66+ // Update database with the new object
67+ rootRef . update ( updateObject ) . catch ( error => console . log ( error ) ) ;
68+
69+ // Success Message
70+ res . status ( 201 ) . json ( {
71+ success : `Message has been sent.` ,
72+ } ) ;
73+ }
74+ ) ;
75+
76+ module . exports = router ;
0 commit comments