controller.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /**
  2. * @Author HonorLee (dev@honorlee.me)
  3. * @Version 1.0 (2018-05-04)
  4. * @License MIT
  5. */
  6. export default class Controller{
  7. private _requestData:RequestData;
  8. private _Request:any;
  9. private _Response:any;
  10. public REFERER:string;
  11. public REQPATH:string;
  12. public REQMETHOD:string;
  13. public REQTIME:number;
  14. public COOKIE:any;
  15. public GET:any;
  16. public POST:any;
  17. public UPLOAD:any;
  18. public SESSION:any;
  19. public DATA:AnyKeyString;
  20. constructor(requestData:RequestData) {
  21. this._requestData = requestData;
  22. this._Request = requestData.req;
  23. this._Response = requestData.res;
  24. this.REFERER = this._Request.headers.referer;
  25. this.REQPATH = requestData.path||'';
  26. this.REQMETHOD = requestData.method;
  27. this.REQTIME = Moment().unix();
  28. this.COOKIE = requestData.COOKIE;
  29. this.GET = requestData.GET;
  30. this.POST = requestData.POST;
  31. this.UPLOAD = requestData.UPLOAD;
  32. this.SESSION = requestData.SESSION;
  33. this.DATA = {};
  34. if(this.GET._time) delete this.GET._time;
  35. if(this.POST._time) delete this.POST._time;
  36. // console.log(this._constructor)
  37. }
  38. /**
  39. * [response description]
  40. * @return {[type]} [description]
  41. */
  42. end(data:any,status?:number,mime?:string):void{
  43. let endContent = data,statusCode = 200,mimeType = 'text/plain';
  44. if(!endContent) endContent = '';
  45. if(typeof endContent == 'number') endContent = `${endContent}`;
  46. if(status) statusCode = status;
  47. if(mime) mimeType = mime;
  48. if(status) this._Response.statusCode = status;
  49. if(mimeType) this._Response.setHeader('Content-Type', `${mimeType}; charset=UTF-8`);
  50. try{
  51. this._Response.write(endContent);
  52. this._Response.end();
  53. }catch(e:any){
  54. LOGGER.error(e.stack)
  55. }
  56. }
  57. endRedirect(location:string,permanently?:boolean){
  58. const status = permanently?301:302;
  59. this._Response.writeHead(status,{'Location':location});
  60. this._Response.end();
  61. }
  62. /**
  63. * [responseInJSON description]
  64. * @param {[type]} somthing [String,Number,Object]
  65. */
  66. endJSON(somthing:any){
  67. let endContent;
  68. if(typeof somthing == 'string' || typeof somthing == 'number'){
  69. endContent = {data:somthing};
  70. }else if(typeof somthing == 'object'){
  71. endContent = somthing;
  72. }else{
  73. return this._error(new Error('Function endInJSON argument type must be string,number or object'));
  74. }
  75. this.end(JSON.stringify(endContent),200,'text/json');
  76. }
  77. /**
  78. * [responseAPI description]
  79. * @param {[type]} errorCode [description]
  80. * @param {[type]} somthing [description]
  81. */
  82. endAPI(errorCode:number,somthing:any){
  83. const endContent = {error:errorCode,data:null};
  84. if(typeof somthing == 'string' || typeof somthing == 'number' || typeof somthing == 'object'){
  85. endContent.data = somthing;
  86. this.end(JSON.stringify(endContent),200,'text/json');
  87. }else{
  88. this._error(new Error('Function endAPI argument type must be string,number or object'));
  89. }
  90. }
  91. /**
  92. * [responseAPI description]
  93. * @param {[type]} errorCode [description]
  94. * @param {[type]} somthing [description]
  95. */
  96. endView(viewname:string,data?:any,option?:any){
  97. const viewFilePath = `${SYSTEM.MVC.PATH.VIEW}/${viewname}`;
  98. let tpl;
  99. try{
  100. tpl = FILE.readFileSync(`${viewFilePath}.html`,'utf-8');
  101. }catch(e){
  102. try{
  103. tpl = FILE.readFileSync(`${viewFilePath}.tpl`,'utf-8');
  104. }catch(e){
  105. }
  106. }
  107. if(!tpl) return this.end(`View template [${viewname}] not exist!`);
  108. const render = SYSTEM.MVC.EJS.compile(tpl,option);
  109. const renderedTpl = render(data);
  110. this.end(renderedTpl,200,'text/html');
  111. }
  112. /**
  113. * [responseView description]
  114. * @param {[type]} viewName [description]
  115. * @param {[type]} data [description]
  116. * @return {[type]} [description]
  117. */
  118. // endView(viewName,data){
  119. // let view = new VIEW(viewName,data);
  120. // if(view && view.html){
  121. // this.end(200,view.html,'text/html');
  122. // }else{
  123. // this.end(502,`View [${viewName}] not found`,'text/plain');
  124. // }
  125. // }
  126. setCookie(key:string,value:any,expireHour?:number|'forever',path?:string,httpOnly?:boolean){
  127. let cookie,originCookie;
  128. if(this._Response.hasHeader('Set-Cookie')){
  129. originCookie = this._Response.getHeader('Set-Cookie');
  130. }
  131. if(!originCookie) originCookie = [];
  132. if(typeof originCookie == 'string') originCookie = [originCookie];
  133. cookie = `${key}=${value}`;
  134. cookie += ';path=' + (path||'/');
  135. expireHour = expireHour!=undefined&&expireHour>=0?expireHour:'forever';
  136. let expireTime;
  137. if(expireHour=='forever'){
  138. expireTime = new Date('9999/01/01 00:00:00').toUTCString();
  139. }else if(expireHour==0){
  140. expireTime = new Date(0).toUTCString();
  141. }else{
  142. expireTime = new Date(new Date().getTime()+Number(expireHour)*1000*60).toUTCString();
  143. }
  144. cookie += ';expires=' + expireTime;
  145. if(httpOnly) cookie += ';httpOnly=true';
  146. originCookie.push(cookie);
  147. this._Response.setHeader('Set-Cookie',cookie);
  148. }
  149. renewCookie(key:string,expire:number|'forever',path?:string){
  150. const originCookieValue = this.COOKIE[key];
  151. if(!originCookieValue) return false;
  152. this.setCookie(key,originCookieValue,expire,path);
  153. }
  154. _error(err:any){
  155. LOGGER.error(err.stack);
  156. this.end(`<center style="font-size:24px">- 403 -</center>`,403,'text/html');
  157. }
  158. }