index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.PRAS = void 0;
  4. class PRAS {
  5. getPRASResultObject(statusCode, status, message, data, code, extra) {
  6. return {
  7. statusCode: statusCode || 200,
  8. status: status || "OK",
  9. message: message || "",
  10. data: data || null,
  11. code: code || "UNKNOWN_CODE",
  12. extra: extra || null,
  13. };
  14. }
  15. responseMiddleware() {
  16. return (req, res, next) => {
  17. res.pras = {
  18. ok: (message, data, code, extra) => {
  19. res.json(this.getPRASResultObject(200, "OK", message, data, code, extra));
  20. },
  21. created: (message, data, code, extra) => {
  22. res.json(this.getPRASResultObject(201, "OK", message, data, code, extra));
  23. },
  24. badRequest: (message, data, code, extra) => {
  25. res.json(this.getPRASResultObject(400, "FAIL", message, data, code, extra));
  26. },
  27. unauthorized: (message, data, code, extra) => {
  28. res.json(this.getPRASResultObject(401, "FAIL", message, data, code, extra));
  29. },
  30. forbidden: (message, data, code, extra) => {
  31. res.json(this.getPRASResultObject(403, "FAIL", message, data, code, extra));
  32. },
  33. notFound: (message, data, code, extra) => {
  34. res.json(this.getPRASResultObject(404, "FAIL", message, data, code, extra));
  35. },
  36. serverError: (message, data, code, extra) => {
  37. res.json(this.getPRASResultObject(500, "ERROR", message, data, code, extra));
  38. },
  39. customMessage: (statusCode, message, data, code, extra) => {
  40. let status;
  41. if (statusCode >= 500) {
  42. status = "ERROR";
  43. }
  44. else if (statusCode >= 400) {
  45. status = "FAIL";
  46. }
  47. else {
  48. status = "OK";
  49. }
  50. res.json(this.getPRASResultObject(statusCode, status, message, data, code, extra));
  51. },
  52. };
  53. next();
  54. };
  55. }
  56. }
  57. exports.PRAS = PRAS;
  58. exports.default = new PRAS();