overleaf/services/chat/app/js/Features/Messages/MessageManager.js

99 lines
2.4 KiB
JavaScript
Raw Normal View History

let MessageManager
const { db, ObjectId } = require('../../mongodb')
const metrics = require('@overleaf/metrics')
const logger = require('@overleaf/logger')
const { callbackify } = require('util')
2014-08-15 05:50:36 -04:00
async function createMessage(roomId, userId, content, timestamp) {
let newMessageOpts = {
content,
room_id: roomId,
user_id: userId,
timestamp,
}
newMessageOpts = _ensureIdsAreObjectIds(newMessageOpts)
const confirmation = await db.messages.insertOne(newMessageOpts)
newMessageOpts._id = confirmation.insertedId
return newMessageOpts
}
2014-08-15 05:50:36 -04:00
async function getMessages(roomId, limit, before) {
let query = { room_id: roomId }
if (before) {
query.timestamp = { $lt: before }
}
query = _ensureIdsAreObjectIds(query)
return db.messages.find(query).sort({ timestamp: -1 }).limit(limit).toArray()
}
async function findAllMessagesInRooms(roomIds) {
return db.messages
.find({
room_id: { $in: roomIds },
})
.toArray()
}
async function deleteAllMessagesInRoom(roomId) {
await db.messages.deleteMany({
room_id: roomId,
})
}
async function updateMessage(roomId, messageId, content, timestamp) {
const query = _ensureIdsAreObjectIds({
_id: messageId,
room_id: roomId,
})
await db.messages.updateOne(query, {
$set: {
content,
edited_at: timestamp,
},
})
}
2017-03-16 12:08:57 -04:00
async function deleteMessage(roomId, messageId) {
const query = _ensureIdsAreObjectIds({
_id: messageId,
room_id: roomId,
})
await db.messages.deleteOne(query)
}
2017-03-17 11:16:38 -04:00
function _ensureIdsAreObjectIds(query) {
if (query.user_id && !(query.user_id instanceof ObjectId)) {
query.user_id = ObjectId(query.user_id)
}
if (query.room_id && !(query.room_id instanceof ObjectId)) {
query.room_id = ObjectId(query.room_id)
}
if (query._id && !(query._id instanceof ObjectId)) {
query._id = ObjectId(query._id)
}
return query
}
module.exports = MessageManager = {
createMessage: callbackify(createMessage),
getMessages: callbackify(getMessages),
findAllMessagesInRooms: callbackify(findAllMessagesInRooms),
deleteAllMessagesInRoom: callbackify(deleteAllMessagesInRoom),
updateMessage: callbackify(updateMessage),
deleteMessage: callbackify(deleteMessage),
}
;[
'createMessage',
'getMessages',
'findAllMessagesInRooms',
'updateMessage',
2021-07-13 07:04:48 -04:00
'deleteMessage',
].map(method =>
metrics.timeAsyncMethod(
MessageManager,
method,
'mongo.MessageManager',
logger
)
)