aboutsummaryrefslogtreecommitdiffstats
path: root/src/controllers/messageController.js
blob: 1e78bced22d64cd80dc6ec7275856f46c7779964 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import Message from "../models/Message.js";
import User from "../models/User.js";

function getMessageById(id) {
    return Message.findById(id).populate('authorId').populate('roomId');
}

function listMessages(opts) {
    const limit = opts.limit || 50;
    const offset = opts.offset || 0;
    const filters = opts.filters || {};

    const query = {};
    if (filters.authorId) {
        query.authorId = filters.authorId;
    }
    if (filters.roomId) {
        query.roomId = filters.roomId;
    }

    return Message.find(query).skip(offset).limit(limit).sort({ createdAt: -1 });
}

function searchMessages(opts) {
    const q = opts.q || '';
    const filters = opts.filters || {};

    const query = {
        text: { $regex: q, $options: 'i' }
    };
    if (filters.roomId) {
        query.roomId = filters.roomId;
    }

    return Message.find(query).sort({ createdAt: -1 });
}

async function createMessage(data) {
    const author = await User.findById(data.authorId);
    if (!author) {
        return { error: 'author_not_found' };
    }
    const message = new Message(data);
    return message.save();
}

function updateMessage(id, updates) {
    return Message.findByIdAndUpdate(id, updates, { new: true });
}

function deleteMessage(id) {
    return Message.findByIdAndDelete(id);
}

export { getMessageById, listMessages, searchMessages, createMessage, updateMessage, deleteMessage };