2024-08-21 21:22:59 +03:30
|
|
|
const { validationResult } = require("express-validator");
|
|
|
|
const signale = require("signale");
|
|
|
|
|
2024-09-09 18:43:12 +03:30
|
|
|
const { logger } = require("../config/winston");
|
2024-09-12 14:26:39 +03:30
|
|
|
const { CustomError } = require("../utils");
|
2024-08-21 21:22:59 +03:30
|
|
|
const env = require("../env");
|
|
|
|
|
2024-09-12 14:26:39 +03:30
|
|
|
function ip(req, res, next) {
|
|
|
|
req.realIP = req.headers["x-real-ip"] || req.connection.remoteAddress || "";
|
|
|
|
return next();
|
|
|
|
};
|
2024-08-21 21:22:59 +03:30
|
|
|
|
|
|
|
function error(error, req, res, _next) {
|
|
|
|
if (env.isDev) {
|
|
|
|
signale.fatal(error);
|
|
|
|
}
|
|
|
|
|
|
|
|
const message = error instanceof CustomError ? error.message : "An error occurred.";
|
|
|
|
const statusCode = error.statusCode ?? 500;
|
|
|
|
|
|
|
|
if (req.isHTML && req.viewTemplate) {
|
|
|
|
res.render(req.viewTemplate, { error: message });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-08-31 12:19:39 +03:30
|
|
|
return res.status(statusCode).json({ error: message });
|
2024-08-21 21:22:59 +03:30
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
function verify(req, res, next) {
|
|
|
|
const result = validationResult(req);
|
|
|
|
if (result.isEmpty()) return next();
|
|
|
|
|
|
|
|
const errors = result.array();
|
|
|
|
const error = errors[0].msg;
|
|
|
|
|
|
|
|
res.locals.errors = {};
|
|
|
|
errors.forEach(e => {
|
|
|
|
if (res.locals.errors[e.param]) return;
|
|
|
|
res.locals.errors[e.param] = e.msg;
|
|
|
|
});
|
|
|
|
|
|
|
|
throw new CustomError(error, 400);
|
|
|
|
}
|
|
|
|
|
2024-08-31 12:19:39 +03:30
|
|
|
function parseQuery(req, res, next) {
|
2024-08-21 21:22:59 +03:30
|
|
|
const { admin } = req.user || {};
|
|
|
|
|
|
|
|
if (
|
|
|
|
typeof req.query.limit !== "undefined" &&
|
|
|
|
typeof req.query.limit !== "string"
|
|
|
|
) {
|
|
|
|
return res.status(400).json({ error: "limit query is not valid." });
|
|
|
|
}
|
|
|
|
|
|
|
|
if (
|
|
|
|
typeof req.query.skip !== "undefined" &&
|
|
|
|
typeof req.query.skip !== "string"
|
|
|
|
) {
|
|
|
|
return res.status(400).json({ error: "skip query is not valid." });
|
|
|
|
}
|
|
|
|
|
|
|
|
if (
|
|
|
|
typeof req.query.search !== "undefined" &&
|
|
|
|
typeof req.query.search !== "string"
|
|
|
|
) {
|
|
|
|
return res.status(400).json({ error: "search query is not valid." });
|
|
|
|
}
|
|
|
|
|
|
|
|
const limit = parseInt(req.query.limit) || 10;
|
|
|
|
|
|
|
|
req.context = {
|
|
|
|
limit: limit > 50 ? 50 : limit,
|
2024-09-12 14:26:39 +03:30
|
|
|
skip: parseInt(req.query.skip) || 0,
|
2024-09-08 14:10:02 +03:30
|
|
|
all: admin ? req.query.all === "true" || req.query.all === "on" : false
|
2024-08-21 21:22:59 +03:30
|
|
|
};
|
|
|
|
|
|
|
|
next();
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
error,
|
2024-09-12 14:26:39 +03:30
|
|
|
ip,
|
2024-08-31 12:19:39 +03:30
|
|
|
parseQuery,
|
2024-08-21 21:22:59 +03:30
|
|
|
verify,
|
|
|
|
}
|