akf-forum/routes/search.js

54 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-09-01 16:23:46 +03:00
const { UserModel, ThreadModel, MessageModel } = require("../models")
const { Router } = require("express");
const app = Router();
app.get("/", (req, res) => res.reply("search"));
2022-09-09 18:27:41 +03:00
app.use(async (req, res, next) => {
req.sq = {}
req.page = Number(req.query.page) || 0;
req.so = { limit: 10, skip: req.page * 10 }
if (!req.user?.admin) req.sq.deleted = false;
next();
});
2022-09-01 16:23:46 +03:00
app.get("/users", async (req, res) => {
if (!req.query.q) return res.error(400, "Missing query parameter 'q' in request body.");
2022-09-09 18:27:41 +03:00
const users = await UserModel.find({ ...req.sq, name: { $regex: req.query.q, $options: "i" } }, null, req.so)
res.reply("users", {
users, page: req.page,
pages: Math.ceil(await UserModel.count(req.sq) / 10)
});
2022-09-01 16:23:46 +03:00
});
2022-09-01 16:23:46 +03:00
app.get("/messages", async (req, res) => {
if (!Object.values(req.query).length) return res.error(400, "Missing query parameters in request body.");
2022-09-09 18:27:41 +03:00
const query = { ...req.sq };
2022-09-01 16:23:46 +03:00
if (req.query.q) query.content = { $regex: req.query.q, $options: "i" };
if (req.query.authorID) query.authorID = req.query.authorID;
2022-09-09 18:27:41 +03:00
const messages = await MessageModel.find(query, null, req.so)
res.reply("messages", {
messages, page: req.page,
pages: Math.ceil(await MessageModel.count(query) / 10)
});
2022-09-01 16:23:46 +03:00
});
2022-09-01 16:23:46 +03:00
app.get("/threads", async (req, res) => {
if (!Object.values(req.query).length) return res.error(400, "Missing query parameters in request body.");
2022-09-21 23:54:48 +03:00
const query = {};
if (!req.user?.admin) query.state = "OPEN";
2022-09-01 16:23:46 +03:00
if (req.query.q) query.title = { $regex: req.query.q, $options: "i" };
if (req.query.authorID) query.authorID = req.query.authorID;
2022-09-09 18:27:41 +03:00
const threads = await ThreadModel.find(query, null, req.so)
res.reply("threads", {
2022-09-16 23:51:16 +03:00
threads, page: req.page, title: `Threads with query '${req.query.q}'`,
pages: Math.ceil(await ThreadModel.count(query) / 10), desp: `${threads.length} threads are listed`
2022-09-09 18:27:41 +03:00
});
2022-09-01 16:23:46 +03:00
});
module.exports = app;