Response.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. "use strict";
  2. var CallLog = require('./CallLog.js');
  3. class Response {
  4. constructor(req, res) {
  5. this._req = req;
  6. this._res = res;
  7. this.codeMap = require('../../conf/code.inc.js');
  8. }
  9. /**
  10. * sucess
  11. * @param {Array|String|Number} data 返回的数据
  12. * @param {String} msg 返回的msg
  13. * @param {String} debugMsg 调试的msg
  14. * @author benzhan
  15. */
  16. success(data, msg, debugMsg) {
  17. var code = CODE_SUCCESS;
  18. this.debugMsg = debugMsg;
  19. msg = msg || this.codeMap[code];
  20. if (global['DEBUG'] && debugMsg) {
  21. msg = msg + " 【调试信息:" + debugMsg + "】";
  22. }
  23. var ret = {
  24. result: 1,
  25. code: code,
  26. msg: msg,
  27. data: data
  28. };
  29. this.exitData(ret);
  30. }
  31. /**
  32. * error with code
  33. * @param {Number} code
  34. * @param {String} msg
  35. * @param {String} debugMsg
  36. * @param {String} extData
  37. * @author benzhan
  38. */
  39. error(code, msg, debugMsg, extData) {
  40. this.debugMsg = debugMsg;
  41. msg = msg || this.codeMap[code];
  42. if (global['DEBUG'] && debugMsg) {
  43. msg = msg + " 【调试信息:" + debugMsg + "】";
  44. }
  45. var ret = {
  46. result: 0,
  47. code: code,
  48. msg: msg
  49. };
  50. if (extData) {
  51. ret['data'] = extData;
  52. }
  53. this.exitData(ret);
  54. }
  55. exitData(ret) {
  56. var json = JSON.stringify(ret);
  57. if (!this._res._headerSent) {
  58. this._res.header('Content-Type', 'application/json;charset=utf8');
  59. }
  60. this.exitMsg(json, ret['code']);
  61. }
  62. exitMsg(content, code) {
  63. var res = this._res;
  64. var req = this._req;
  65. code = code || CODE_SUCCESS;
  66. //必须是字符串
  67. if (typeof content != "string") {
  68. content = JSON.stringify(content);
  69. }
  70. //jquery jsonp callback处理
  71. if (req.query && req.query.callback) {
  72. if (/^jQuery(\d+)_(\d+)$/.test(req.query.callback)) {
  73. content = req.query.callback + '(' + content + ');';
  74. }
  75. }
  76. // 记录访问日志
  77. var objCallLog = new CallLog(this);
  78. objCallLog.logSelfCall(code, content);
  79. if (!res.finished) {
  80. res.write(content);
  81. res.end();
  82. }
  83. }
  84. }
  85. module.exports = Response;