helpers.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { Handler, ErrorRequestHandler } from "express";
  2. import { validationResult } from "express-validator";
  3. import * as Sentry from "@sentry/node";
  4. import signale from "signale";
  5. import { CustomError } from "../utils";
  6. import env from "../env";
  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. if (env.isDev) {
  14. signale.fatal(error);
  15. }
  16. if (error instanceof CustomError) {
  17. return res.status(error.statusCode || 500).json({ error: error.message });
  18. }
  19. if (env.SENTRY_PRIVATE_DSN) {
  20. Sentry.captureException(error);
  21. }
  22. return res.status(500).json({ error: "An error occurred." });
  23. };
  24. export const verify = (req, res, next) => {
  25. const errors = validationResult(req);
  26. if (!errors.isEmpty()) {
  27. const message = errors.array()[0].msg;
  28. throw new CustomError(message, 400);
  29. }
  30. return next();
  31. };
  32. export const query: Handler = (req, res, next) => {
  33. const { limit, skip, all } = req.query;
  34. const { admin } = req.user || {};
  35. req.query.limit = parseInt(limit) || 10;
  36. req.query.skip = parseInt(skip) || 0;
  37. if (req.query.limit > 50) {
  38. req.query.limit = 50;
  39. }
  40. req.query.all = admin ? all === "true" : false;
  41. next();
  42. };