helpers.ts 1.8 KB

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