Response.js 2.2 KB

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