Untitled

 avatar
unknown
plain_text
14 days ago
7.0 kB
3
Indexable
router.post(
    "/get_conversations",
    permissionCheck("MODERATOR"),
    async (req, res) => {
        try {
            var { lastUpdatedDate, search, countries } = req.body;
            var { mode } = req.query;
            var Result = {};

            var Filter = {
                lastMessage: { $ne: null },
                lastMessageFrom: { $ne: "system" },
                isBot: true,
                Admin: req.decoded._id,
            };

            var effectiveLimit = null;
            if (mode == "admin") {
                if (!permissionCheck("IZLEYICI_MODU")) {
                    throw "You are not authorized to access this mode!";
                }

                // izleyici modu
                effectiveLimit = req.query.limit || 20;

                delete Filter.Admin;
            }

            var firstItem = await ConversationModel.findOne(Filter)
                .select("_id")
                .sort({
                    updatedDate: 1,
                });

            if (lastUpdatedDate && lastUpdatedDate != "null") {
                Filter.updatedDate = { $lt: lastUpdatedDate };
            }

            if (!empty(search)) {
                Filter.$or = [{ Name: { $regex: new RegExp(search, "i") } }];
            }

            let getConversations;
            let totalCount;

            if (countries && Array.isArray(countries) && countries.length > 0) {
                // Minimal aggregation pipeline with only essential data
                const pipeline = [
                    { $match: Filter },
                    {
                        $lookup: {
                            from: "User",
                            let: { participantIds: "$participants" },
                            pipeline: [
                                {
                                    $match: {
                                        $expr: { $in: ["$_id", "$$participantIds"] },
                                        country: { $in: countries.map(id => new mongoose.Types.ObjectId(id)) }
                                    }
                                },
                                {
                                    $project: {
                                        _id: 1,
                                        name: 1,
                                        isBot: 1,
                                        photos: 1
                                    }
                                }
                            ],
                            as: "participants"
                        }
                    },
                    {
                        $match: {
                            "participants": { $ne: [] }
                        }
                    },
                    {
                        $lookup: {
                            from: "Message",
                            let: { msgId: "$lastMessage" },
                            pipeline: [
                                {
                                    $match: {
                                        $expr: { $eq: ["$_id", "$$msgId"] }
                                    }
                                },
                                {
                                    $project: {
                                        _id: 1,
                                        message: 1,
                                        createdDate: 1
                                    }
                                }
                            ],
                            as: "lastMessage"
                        }
                    },
                    {
                        $project: {
                            _id: 1,
                            lastMessage: { $arrayElemAt: ["$lastMessage", 0] },
                            Admin: 1,
                            participants: 1,
                            updatedDate: 1,
                            createdDate: 1,
                            isBot: 1,
                            lastMessageFrom: 1
                        }
                    },
                    { $sort: { updatedDate: -1 } }
                ];

                if (effectiveLimit) {
                    pipeline.push({ $limit: effectiveLimit });
                }

                getConversations = await ConversationModel.aggregate(pipeline);

                // Simplified count pipeline
                const countPipeline = [
                    { $match: Filter },
                    {
                        $lookup: {
                            from: "User",
                            let: { participantIds: "$participants" },
                            pipeline: [
                                {
                                    $match: {
                                        $expr: { $in: ["$_id", "$$participantIds"] },
                                        country: { $in: countries.map(id => new mongoose.Types.ObjectId(id)) }
                                    }
                                }
                            ],
                            as: "participants"
                        }
                    },
                    {
                        $match: {
                            "participants": { $ne: [] }
                        }
                    },
                    { $count: "total" }
                ];
                
                const countResult = await ConversationModel.aggregate(countPipeline);
                totalCount = countResult.length > 0 ? countResult[0].total : 0;
            } else {
                // Use regular find query when no country filter
                getConversations = await ConversationModel.find(Filter)
                    .populate({
                        path: "lastMessage",
                    })
                    .populate({
                        path: "Admin",
                        select: "_id Name",
                    })
                    .populate({
                        path: "participants",
                        populate: [
                            {
                                path: "photos",
                            },
                        ],
                    })
                    .sort({ updatedDate: -1 })
                    .limit(effectiveLimit);

                totalCount = await ConversationModel.countDocuments(Filter);
            }

            Result.chats = getConversations;
            Result.status = true;
            Result.firstItem = firstItem;
            Result.pagination = {
                limit: effectiveLimit,
                total: totalCount
            };

            res.status(200).send(Result);
        } catch (e) {
            console.log("err", e);
            res.send({ status: false, msg: e });
        }
    }
);
Editor is loading...
Leave a Comment