Skip to content

1553 persist chat #1568

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions api/main_endpoints/models/ChatMessage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ChatMessageSchema = new Schema(
{
userId: {
type: String,
required: true,
},
text: {
type: String,
required: true,
maxLength: [2000, 'Messages are at most 2000 characters long']
},
chatRoomId: {
type: String,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
expireAt: {
type: Date,
default: () => new Date(Date.now() + 24 * 60 * 60 * 1000)
}
},
{ collection: 'ChatMessage' }
);
ChatMessageSchema.index({ createdAt: 1, chatRoomId: 1 }); // schema level compound index

module.exports = mongoose.model('ChatMessage', ChatMessageSchema);
77 changes: 45 additions & 32 deletions api/main_endpoints/routes/Messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,39 +13,45 @@ const logger = require('../../util/logger');
const client = require('prom-client');
const { decodeToken, decodeTokenFromBodyOrQuery } = require('../util/token-functions.js');
const { MetricsHandler, register } = require('../../util/metrics.js');

const ChatMessage = require('../models/ChatMessage.js');

router.use(bodyParser.json());



const clients = {};
const numberOfConnections = {};
const lastMessageSent = {};

const writeMessage = ((roomId, message, username) => {
const writeMessage = async (roomId, message, username) => {
const messageObj = new ChatMessage({
userId: username,
text: message,
chatRoomId: roomId,
});

await messageObj.save();

const messageObj = {
timestamp: Date.now(),
message,
username
const messageToSend = {
username: username,
message: message,
timestamp: messageObj.createdAt.getTime(), // Convert to timestamp for frontend
chatRoomId: roomId
};


if (clients[roomId]) {
clients[roomId].forEach(res => res.write(`data: ${JSON.stringify(messageObj)}\n\n`));
clients[roomId].forEach(res => res.write(`data: ${JSON.stringify(messageToSend)}\n\n`));
}

lastMessageSent[roomId] = JSON.stringify(messageObj);
lastMessageSent[roomId] = JSON.stringify(messageToSend);

// increase the total messages sent counter
MetricsHandler.totalMessagesSent.inc();

// increase the total amount of messages sent per chatroom counter
MetricsHandler.totalChatMessagesPerChatRoom.labels(roomId).inc();
});
};

router.post('/send', async (req, res) => {

const {message, id} = req.body;
const token = req.headers['authorization'];
const apiKey = req.headers['x-api-key'];
Expand Down Expand Up @@ -83,19 +89,25 @@ router.post('/send', async (req, res) => {
return;
}
if (result) {
writeMessage(id, `${message}`, `${result.firstName}:`);
writeMessage(id, `${message}`, `${result.firstName}`);
return res.json({status: 'Message sent'});
}
return res.sendStatus(UNAUTHORIZED);
});


} catch (error) {
logger.error('Error in /send: ', error);
res.sendStatus(SERVER_ERROR);
}
});


router.get('/getLatestMessage', async (req, res) => {
const {apiKey, id} = req.query;
const {
apiKey,
id
} = req.query;

const required = [
{value: apiKey, title: 'API Key'},
Expand All @@ -104,36 +116,37 @@ router.get('/getLatestMessage', async (req, res) => {

const missingValue = required.find(({value}) => !value);

if (missingValue){
res.status(BAD_REQUEST).send(`You must specify a ${missingValue.title}`);
return;
if (missingValue) {
return res.status(BAD_REQUEST).send(`You must specify a ${missingValue.title}`);
}

try {
User.findOne({ apiKey }, (error, result) => {
if (error) {
logger.error('/listen received an invalid API key: ', error);
res.sendStatus(SERVER_ERROR);
return;
}
// Using async/await with proper error handling
const user = await User.findOne(
{ apiKey }
);

if (!result) { // return unauthorized if no api key found
return res.sendStatus(UNAUTHORIZED);
}
if (!user) {
return res.sendStatus(UNAUTHORIZED);
}

if (!lastMessageSent[id]) {
return res.status(OK).send('Room closed');
}

return res.status(OK).send(lastMessageSent[id]);
const latestMessage = await ChatMessage.find({ chatRoomId: id })
.sort({ createdAt: -1 });

if (!latestMessage) {
return res.status(OK).send('Room closed');
}

return res.status(OK).json(latestMessage);

});
} catch (error) {
logger.error('Error in /get: ', error);
res.sendStatus(SERVER_ERROR);
return res.sendStatus(SERVER_ERROR);
}
});


router.get('/listen', async (req, res) => {

const {token, apiKey, id} = req.query;
Expand Down