helpers.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const { validationResult } = require("express-validator");
  2. const signale = require("signale");
  3. const { logger } = require("../config/winston");
  4. const { CustomError } = require("../utils");
  5. const env = require("../env");
  6. // export const ip: Handler = (req, res, next) => {
  7. // req.realIP =
  8. // (req.headers["x-real-ip"] as string) || req.connection.remoteAddress || "";
  9. // return next();
  10. // };
  11. /**
  12. * @type {import("express").ErrorRequestHandler}
  13. */
  14. function error(error, _req, res, _next) {
  15. if (env.isDev) {
  16. signale.fatal(error);
  17. }
  18. if (error instanceof CustomError) {
  19. return res.status(error.statusCode || 500).json({ error: error.message });
  20. }
  21. return res.status(500).json({ error: "An error occurred." });
  22. };
  23. function verify(template) {
  24. return function (req, res, next) {
  25. const errors = validationResult(req);
  26. if (!errors.isEmpty()) {
  27. const accepts = req.accepts(["json", "html"]);
  28. const message = errors.array()[0].msg;
  29. if (template && accepts === "html") {
  30. return res.render(template, {
  31. layout: null,
  32. error: message
  33. });
  34. }
  35. throw new CustomError(message, 400);
  36. }
  37. return next();
  38. }
  39. }
  40. // export const query: Handler = (req, res, next) => {
  41. // const { admin } = req.user || {};
  42. // if (
  43. // typeof req.query.limit !== "undefined" &&
  44. // typeof req.query.limit !== "string"
  45. // ) {
  46. // return res.status(400).json({ error: "limit query is not valid." });
  47. // }
  48. // if (
  49. // typeof req.query.skip !== "undefined" &&
  50. // typeof req.query.skip !== "string"
  51. // ) {
  52. // return res.status(400).json({ error: "skip query is not valid." });
  53. // }
  54. // if (
  55. // typeof req.query.search !== "undefined" &&
  56. // typeof req.query.search !== "string"
  57. // ) {
  58. // return res.status(400).json({ error: "search query is not valid." });
  59. // }
  60. // const limit = parseInt(req.query.limit) || 10;
  61. // const skip = parseInt(req.query.skip) || 0;
  62. // req.context = {
  63. // limit: limit > 50 ? 50 : limit,
  64. // skip,
  65. // all: admin ? req.query.all === "true" : false
  66. // };
  67. // next();
  68. // };
  69. module.exports = {
  70. error,
  71. verify,
  72. }