overleaf/services/chat/app/js/Features/Threads/ThreadManager.js

139 lines
2.9 KiB
JavaScript
Raw Normal View History

let ThreadManager
const { db, ObjectId } = require('../../mongodb')
const logger = require('@overleaf/logger')
const metrics = require('@overleaf/metrics')
module.exports = ThreadManager = {
GLOBAL_THREAD: 'GLOBAL',
findOrCreateThread(projectId, threadId, callback) {
let query, update
if (!callback) {
callback = function () {}
}
projectId = ObjectId(projectId.toString())
if (threadId !== ThreadManager.GLOBAL_THREAD) {
threadId = ObjectId(threadId.toString())
}
if (threadId === ThreadManager.GLOBAL_THREAD) {
query = {
project_id: projectId,
2021-07-13 07:04:48 -04:00
thread_id: { $exists: false },
}
update = {
project_id: projectId,
}
} else {
query = {
project_id: projectId,
thread_id: threadId,
}
update = {
project_id: projectId,
thread_id: threadId,
}
}
db.rooms.findOneAndUpdate(
2021-07-13 07:04:48 -04:00
query,
{ $set: update },
{ upsert: true, returnDocument: 'after' },
function (error, result) {
if (error) {
2021-07-13 07:04:48 -04:00
return callback(error)
}
callback(null, result.value)
}
2021-07-13 07:04:48 -04:00
)
},
2017-03-16 12:08:57 -04:00
findAllThreadRooms(projectId, callback) {
if (!callback) {
callback = function () {}
}
db.rooms
.find(
{
project_id: ObjectId(projectId.toString()),
2021-07-13 07:04:48 -04:00
thread_id: { $exists: true },
},
{
thread_id: 1,
2021-07-13 07:04:48 -04:00
resolved: 1,
}
)
.toArray(callback)
},
2017-03-16 12:08:57 -04:00
resolveThread(projectId, threadId, userId, callback) {
if (!callback) {
callback = function () {}
}
db.rooms.updateOne(
{
project_id: ObjectId(projectId.toString()),
thread_id: ObjectId(threadId.toString()),
},
{
$set: {
resolved: {
user_id: userId,
2021-07-13 07:04:48 -04:00
ts: new Date(),
},
},
},
callback
)
},
reopenThread(projectId, threadId, callback) {
if (!callback) {
callback = function () {}
}
db.rooms.updateOne(
{
project_id: ObjectId(projectId.toString()),
thread_id: ObjectId(threadId.toString()),
},
{
$unset: {
2021-07-13 07:04:48 -04:00
resolved: true,
},
},
callback
)
},
deleteThread(projectId, threadId, callback) {
if (!callback) {
callback = function () {}
}
this.findOrCreateThread(projectId, threadId, function (error, room) {
if (error) {
return callback(error)
2021-07-13 07:04:48 -04:00
}
db.rooms.deleteOne(
{
_id: room._id,
},
function (error) {
if (error) {
return callback(error)
}
callback(null, room._id)
}
)
})
2021-07-13 07:04:48 -04:00
},
}
;[
'findOrCreateThread',
'findAllThreadRooms',
'resolveThread',
'reopenThread',
2021-07-13 07:04:48 -04:00
'deleteThread',
].map(method =>
metrics.timeAsyncMethod(ThreadManager, method, 'mongo.ThreadManager', logger)
)