handler.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * @Author HonorLee (deve@honorlee.me)
  3. * @Version 1.0 (2018-05-04)
  4. * @License MIT
  5. */
  6. 'use strict'
  7. module.exports = function(req,res){
  8. this.Request = req;
  9. this.Response = res;
  10. this.COOKIE = req._Cookie;
  11. this.GET = req._GET;
  12. this.POST = req._POST;
  13. this.UPLOAD = req._UPLOAD;
  14. /**
  15. * [response description]
  16. * @return {[type]} [description]
  17. */
  18. this.end = this.response = function(){
  19. let mimeType = 'text/plain';
  20. let status = 200;
  21. let endContent = '';
  22. switch(arguments.length){
  23. case 1:
  24. endContent = arguments[0];
  25. break;
  26. case 2:
  27. status = arguments[0];
  28. endContent = arguments[1];
  29. break;
  30. case 3:
  31. status = arguments[0];
  32. endContent = arguments[1];
  33. mimeType = arguments[2];
  34. break;
  35. }
  36. this.Response.writeHead(status, { 'Content-Type': `${mimeType}; charset=UTF-8`});
  37. this.Response.write(endContent);
  38. this.Response.end();
  39. }
  40. /**
  41. * [responseInJSON description]
  42. * @param {[type]} somthing [String,Number,Object]
  43. */
  44. this.endJSON = this.responseInJSON = function(somthing){
  45. let endContent;
  46. if(typeof somthing == 'string' || typeof somthing == 'number'){
  47. endContent = {data:somthing};
  48. }else if(typeof somthing == 'object'){
  49. endContent = somthing;
  50. }else{
  51. return LOGGER.error('Function endInJSON argument type must be string,number or object');
  52. }
  53. this.end(200,JSON.stringify(endContent),'text/json');
  54. }
  55. /**
  56. * [responseAPI description]
  57. * @param {[type]} statusCode [description]
  58. * @param {[type]} somthing [description]
  59. */
  60. this.endAPI = this.responseAPI = function(statusCode,somthing){
  61. let endContent = {statusCode:statusCode,data:null};
  62. if(typeof somthing == 'string' || typeof somthing == 'number' || typeof somthing == 'object'){
  63. endContent.data = somthing;
  64. this.end(200,JSON.stringify(endContent),'text/json');
  65. }else{
  66. return LOGGER.error('Function endAPI argument type must be string,number or object');
  67. }
  68. }
  69. /**
  70. * [responseView description]
  71. * @param {[type]} viewName [description]
  72. * @param {[type]} data [description]
  73. * @return {[type]} [description]
  74. */
  75. this.endView = this.responseView = function(viewName,data){
  76. let view = new VIEW(viewName,data);
  77. if(view && view.html){
  78. this.end(200,view.html,'text/html');
  79. }else{
  80. this.end(403,`View [${viewName}] not found`);
  81. }
  82. }
  83. }