helpers.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // eslint-disable-next-line
  13. export const error: ErrorRequestHandler = (error, _req, res, _next) => {
  14. logger.error(error);
  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. export const verify = (req, res, next) => {
  24. const errors = validationResult(req);
  25. if (!errors.isEmpty()) {
  26. const message = errors.array()[0].msg;
  27. throw new CustomError(message, 400);
  28. }
  29. return next();
  30. };
  31. export const query: Handler = (req, res, next) => {
  32. const { admin } = req.user || {};
  33. if (
  34. typeof req.query.limit !== "undefined" &&
  35. typeof req.query.limit !== "string"
  36. ) {
  37. return res.status(400).json({ error: "limit query is not valid." });
  38. }
  39. if (
  40. typeof req.query.skip !== "undefined" &&
  41. typeof req.query.skip !== "string"
  42. ) {
  43. return res.status(400).json({ error: "skip query is not valid." });
  44. }
  45. if (
  46. typeof req.query.search !== "undefined" &&
  47. typeof req.query.search !== "string"
  48. ) {
  49. return res.status(400).json({ error: "search query is not valid." });
  50. }
  51. const limit = parseInt(req.query.limit) || 10;
  52. const skip = parseInt(req.query.skip) || 0;
  53. req.context = {
  54. limit: limit > 50 ? 50 : limit,
  55. skip,
  56. all: admin ? req.query.all === "true" : false
  57. };
  58. next();
  59. };