index.js 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.PRAS = void 0;
  4. class PRAS {
  5. getPRASResultObject(statusCode = 200, status = "OK", message = "", data = null, code = "UNKNOWN_CODE", extra = null) {
  6. return {
  7. statusCode,
  8. status,
  9. message,
  10. data,
  11. code,
  12. extra,
  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. if (req.rawHeaders.hasOwnProperty("Accept") &&
  54. /application\/json/.test(req.rawHeaders["Accept"])) {
  55. const send = res.send;
  56. res.send = (body) => {
  57. try {
  58. if (typeof body === "string") {
  59. body = JSON.parse(body);
  60. }
  61. if (typeof body === "string") {
  62. body = { data: body };
  63. }
  64. else if (!body.hasOwnProperty("data")) {
  65. body = { data: body };
  66. }
  67. const prasBody = this.getPRASResultObject(body.statusCode, body.status, body.message, body.data, body.code, body.extra);
  68. res.status(prasBody.statusCode || 200);
  69. delete prasBody.statusCode;
  70. return send.call(res, JSON.stringify(prasBody));
  71. }
  72. catch (err) {
  73. return send.call(res, body);
  74. }
  75. };
  76. }
  77. next();
  78. };
  79. }
  80. }
  81. exports.PRAS = PRAS;
  82. exports.default = new PRAS();