Browse Source

New Feature

HonorLee 2 years ago
parent
commit
cc125b251c

+ 1 - 0
package.json

@@ -48,6 +48,7 @@
     "klaw-sync": "^6.0.0",
     "klaw-sync": "^6.0.0",
     "md5": "^2.3.0",
     "md5": "^2.3.0",
     "memcached": "^2.2.2",
     "memcached": "^2.2.2",
+    "moment": "^2.29.4",
     "mongodb": "^4.7.0",
     "mongodb": "^4.7.0",
     "mysql": "^2.18.1",
     "mysql": "^2.18.1",
     "redis": "^4.1.0",
     "redis": "^4.1.0",

+ 6 - 2
source/@types/global.d.ts

@@ -48,6 +48,7 @@ declare global{
         req:IncomingMessage|undefined,
         req:IncomingMessage|undefined,
         res:ServerResponse|undefined,
         res:ServerResponse|undefined,
         path:string|null,
         path:string|null,
+        refer:any,
         method:string,
         method:string,
         COOKIE:any,
         COOKIE:any,
         GET:any,
         GET:any,
@@ -57,6 +58,9 @@ declare global{
     }
     }
     declare class CONTROLLER{
     declare class CONTROLLER{
         REFERER:string;
         REFERER:string;
+        REQPATH:string;
+        REQMETHOD:string;
+        REQTIME:number;
         COOKIE:any;
         COOKIE:any;
         GET:any;
         GET:any;
         POST:any;
         POST:any;
@@ -64,10 +68,10 @@ declare global{
         SESSION:Session;
         SESSION:Session;
         DATA:AnyKeyString;
         DATA:AnyKeyString;
         end(data:any,status?:number,mime?:string):void;
         end(data:any,status?:number,mime?:string):void;
-        endRedirect(location:string,permanently:boolean);
+        endRedirect(location:string,permanently?:boolean);
         endJSON(somthing:any);
         endJSON(somthing:any);
         endAPI(errorCode:number,somthing:any);
         endAPI(errorCode:number,somthing:any);
-        endView(viewname:string,data:any,option?:any);
+        endView(viewname:string,data?:any,option?:any);
         setCookie(key:string,value:any,expire?:number|'forever',path?:string);
         setCookie(key:string,value:any,expire?:number|'forever',path?:string);
         renewCookie(key:string,expire:number|'forever',path?:string);
         renewCookie(key:string,expire:number|'forever',path?:string);
     }
     }

+ 36 - 12
source/system/lib/extra/mysqldb.ts

@@ -45,6 +45,16 @@ export class MysqlDB{
             });
             });
         })
         })
     }
     }
+    async count(tablename:string,whereObj?:any){
+        let whereRule="";
+        if(whereObj){
+            whereRule = ` where ${MysqlUtil.objToKVString(whereObj,' and ')}`;
+        }
+        const sqlStr = `select count(1) as total from ${tablename} ${whereRule}`;
+        const ret = await this.querySync(sqlStr) as MysqlResult;
+        if(ret.err || ret.data.length==0) return 0;
+        return ret.data[0].total;
+    }
     async update(tablename:string,updateObj:any,whereObj:any){
     async update(tablename:string,updateObj:any,whereObj:any){
         if(!tablename || !updateObj) return;
         if(!tablename || !updateObj) return;
         let whereRule="";
         let whereRule="";
@@ -62,7 +72,10 @@ export class MysqlDB{
             return {err:err,data:null};
             return {err:err,data:null};
         }
         }
         let queryStr = "*",whereStr = "";
         let queryStr = "*",whereStr = "";
-        if(queryField) queryStr = queryField.join(",");
+        if(queryField){
+            queryField = queryField.map(v=>`\`${v}\``);
+            queryStr = queryField.join(",");
+        }
         if(whereObj) whereStr = ` where ${MysqlUtil.objToKVString(whereObj,' and ')}`;
         if(whereObj) whereStr = ` where ${MysqlUtil.objToKVString(whereObj,' and ')}`;
 
 
         const sql = `select ${queryStr} from ${tablename} ${whereStr}`;
         const sql = `select ${queryStr} from ${tablename} ${whereStr}`;
@@ -86,16 +99,19 @@ export class MysqlDB{
             const fields = Object.keys(insertData[0]);
             const fields = Object.keys(insertData[0]);
             const values = [];
             const values = [];
             for(const data of insertData){
             for(const data of insertData){
+                const rawData = JSON.parse(JSON.stringify(data));
                 const valueArr = [];
                 const valueArr = [];
                 for(const key of fields){
                 for(const key of fields){
-                    if(data[key] != null || data[key] != undefined){
-                        if(data[key].constructor == String){
-                            data[key] = `"${data[key]}"`;
-                        }else if(data[key].constructor == Number){
-                            data[key] = Number(data[key]);
+                    if(rawData[key] != null || rawData[key] != undefined){
+                        if(rawData[key].constructor == String){
+                            rawData[key] = `"${rawData[key]}"`;
+                        }else if(rawData[key].constructor == Number){
+                            rawData[key] = Number(rawData[key]);
                         }
                         }
+                    }else{
+                        rawData[key] = null;
                     }
                     }
-                    valueArr.push(data[key]);
+                    valueArr.push(rawData[key]);
                 }
                 }
                 values.push(`(${valueArr.join(',')})`);
                 values.push(`(${valueArr.join(',')})`);
             }
             }
@@ -117,20 +133,22 @@ export class MysqlUtil{
     **/
     **/
     public static objToKVString(obj:any,joinStr?:string,keyPrefix?:string){
     public static objToKVString(obj:any,joinStr?:string,keyPrefix?:string){
         const strArr:Array<string> = [];
         const strArr:Array<string> = [];
-
-        const keys = Object.keys(obj);
+        const dupObj = JSON.parse(JSON.stringify(obj));
+        const keys = Object.keys(dupObj);
         let _extraSql = '',_extraLink = '';
         let _extraSql = '',_extraLink = '';
         keyPrefix = keyPrefix?`${keyPrefix}.`:'';
         keyPrefix = keyPrefix?`${keyPrefix}.`:'';
         if(keys.length>0){
         if(keys.length>0){
             keys.forEach(key =>{
             keys.forEach(key =>{
-                let v = obj[key];
+                let v = dupObj[key];
                 if(key=='_extra'){
                 if(key=='_extra'){
                     if(Array.isArray(v)){
                     if(Array.isArray(v)){
                         _extraSql = v.join(joinStr);
                         _extraSql = v.join(joinStr);
                     }else if(v.constructor == Object){
                     }else if(v.constructor == Object){
                         if(v.sql){
                         if(v.sql){
                             _extraSql = v.sql;
                             _extraSql = v.sql;
-                            _extraLink = v.link||'and';
+                            if(v.link!=null){
+                                _extraLink = v.link||'and';
+                            }
                         }
                         }
                     }else{
                     }else{
                         _extraSql = v;
                         _extraSql = v;
@@ -193,7 +211,13 @@ export class MysqlUtil{
                 if(module[key].reverseKey && reverse) key = module[key].reverseKey;
                 if(module[key].reverseKey && reverse) key = module[key].reverseKey;
                 outData[key] = value;
                 outData[key] = value;
             }else{
             }else{
-                if(!filter) outData[key] = data[key];
+                if(!filter){
+                    if(data[key]==null){
+                        outData[key] = String(data[key]);
+                    }else{
+                        outData[key] = data[key];
+                    }
+                }
             }
             }
         })
         })
         return outData;
         return outData;

+ 3 - 3
source/system/lib/helper/wechat/sdk/sdk_mch_redis.ts

@@ -164,16 +164,16 @@ class WechatMchSDK{
     }
     }
 
 
     makeSignPaymentData(prepayId:string){
     makeSignPaymentData(prepayId:string){
-        const randStr = randomStr(32).toUpperCase(),timestamp = Moment().unix(),packageStr = `prepay_id=${prepayId}`;
+        const randStr = randomStr(32).toUpperCase(),timeStamp = Moment().unix(),packageStr = `prepay_id=${prepayId}`;
         let preStr = ''
         let preStr = ''
         preStr += `${this._appId}\n`;
         preStr += `${this._appId}\n`;
-        preStr += `${timestamp}\n`;
+        preStr += `${timeStamp}\n`;
         preStr += `${randStr}\n`;
         preStr += `${randStr}\n`;
         preStr += `${packageStr}\n`;
         preStr += `${packageStr}\n`;
         // console.log(preStr)
         // console.log(preStr)
         const signedStr = this._signWithRSASHA256(preStr);
         const signedStr = this._signWithRSASHA256(preStr);
         // console.log(signedStr)
         // console.log(signedStr)
-        return {timestamp,nonce_str:randStr,signature:signedStr,package:packageStr,prepay_id:prepayId};
+        return {timeStamp:`${timeStamp}`,nonceStr:randStr,paySign:signedStr,package:packageStr,signType:'RSA'};
     }
     }
 
 
     makeSignRequestData(requestUrl:string,method:string,content:AnyKeyString|string){
     makeSignRequestData(requestUrl:string,method:string,content:AnyKeyString|string){

+ 8 - 2
source/system/module/mvc/lib/controller.ts

@@ -8,6 +8,9 @@ export default class Controller{
     private _Request:any;
     private _Request:any;
     private _Response:any;
     private _Response:any;
     public REFERER:string;
     public REFERER:string;
+    public REQPATH:string;
+    public REQMETHOD:string;
+    public REQTIME:number;
     public COOKIE:any;
     public COOKIE:any;
     public GET:any;
     public GET:any;
     public POST:any;
     public POST:any;
@@ -19,6 +22,9 @@ export default class Controller{
         this._Request  = requestData.req;
         this._Request  = requestData.req;
         this._Response = requestData.res;
         this._Response = requestData.res;
         this.REFERER   = this._Request.headers.referer;
         this.REFERER   = this._Request.headers.referer;
+        this.REQPATH   = requestData.path||'';
+        this.REQMETHOD = requestData.method;
+        this.REQTIME   = Moment().unix();
         this.COOKIE    = requestData.COOKIE;
         this.COOKIE    = requestData.COOKIE;
         this.GET       = requestData.GET;
         this.GET       = requestData.GET;
         this.POST      = requestData.POST;
         this.POST      = requestData.POST;
@@ -91,7 +97,7 @@ export default class Controller{
      * @param  {[type]} errorCode [description]
      * @param  {[type]} errorCode [description]
      * @param  {[type]} somthing   [description]
      * @param  {[type]} somthing   [description]
      */
      */
-    endView(viewname:string,data:any,option?:any){
+    endView(viewname:string,data?:any,option?:any){
         const viewFilePath = `${SYSTEM.MVC.PATH.VIEW}/${viewname}`;
         const viewFilePath = `${SYSTEM.MVC.PATH.VIEW}/${viewname}`;
         let tpl;
         let tpl;
         try{
         try{
@@ -105,7 +111,7 @@ export default class Controller{
         if(!tpl) return this.end(`View template [${viewname}] not exist!`);
         if(!tpl) return this.end(`View template [${viewname}] not exist!`);
         const render = SYSTEM.MVC.EJS.compile(tpl,option);
         const render = SYSTEM.MVC.EJS.compile(tpl,option);
         const renderedTpl = render(data);
         const renderedTpl = render(data);
-        this.end(200,renderedTpl,'text/html');
+        this.end(renderedTpl,200,'text/html');
     }
     }
     /**
     /**
      * [responseView description]
      * [responseView description]

+ 18 - 7
source/system/module/mvc/lib/router.ts

@@ -6,9 +6,15 @@
 import PATH = require('path');
 import PATH = require('path');
 
 
 export default class Router{
 export default class Router{
-    private static _midware:any[] = [];
-    public static addMidware(func:any){
-        Router._midware.push(func);
+    private static _midware:any = {};
+    private static _midwareIndex:Array<string> = [];
+    public static setMidware(rule:RegExp,func:any){
+        const reg = rule.toString();
+        if(!Router._midware[reg]){
+            Router._midware[reg] = {exp:rule,handler:[]};
+            Router._midwareIndex.push(reg);
+        }
+        Router._midware[reg].handler.push(func);
     }
     }
     public static async run(requestData:RequestData){
     public static async run(requestData:RequestData){
         let method  = 'index';
         let method  = 'index';
@@ -94,10 +100,15 @@ export default class Router{
         
         
         if(typeof handler[method]==='function'){
         if(typeof handler[method]==='function'){
             let returnSometing;
             let returnSometing;
-            if(Router._midware.length){
-                for(const func of Router._midware){
-                    const ret = func(requestData);
-                    if(ret==false) return;
+            if(requestData.path && Router._midwareIndex.length){
+                for(const reg of Router._midwareIndex){
+                    const match = requestData.path.match(Router._midware[reg].exp);
+                    if(match && match.index==0){
+                        for(const func of Router._midware[reg].handler){
+                            const ret = await func.call(handler,handler);
+                            if(ret==false) return;
+                        }
+                    }
                 }
                 }
             }
             }
             if(typeof handler['__construct']==='function'){
             if(typeof handler['__construct']==='function'){

+ 14 - 3
source/system/module/mvc/lib/session.ts

@@ -22,12 +22,16 @@ export default class Session{
         this._sessionKey = `session_${this.sessionID}`;
         this._sessionKey = `session_${this.sessionID}`;
         this._requestData = requestData;
         this._requestData = requestData;
         if(!sessionID && this._requestData.res){
         if(!sessionID && this._requestData.res){
-            this._requestData.res.setHeader('Set-Cookie',`SESSIONID=${this.sessionID};max-age=${7*24*60*60};path=/;httpOnly=true`);
-            this.set('sessionid',this.sessionID);
-            this.setExpire(7*24*60*60);
+            let sessionCookie = `SESSIONID=${this.sessionID};max-age=${7*24*60*60};path=/`;
+            if(requestData.refer.host) sessionCookie += `;domain=${requestData.refer.host}`;
+            this._requestData.res.setHeader('Set-Cookie',sessionCookie);
         }
         }
     }
     }
     async set(key:string,value:any|null){
     async set(key:string,value:any|null){
+        if(!await SessionManager.check(this._sessionKey)){
+            this.set('sessionid',this.sessionID);
+            this.setExpire(7*24*60*60);
+        }
         return await SessionManager.set(this._sessionKey,key,value);
         return await SessionManager.set(this._sessionKey,key,value);
     }
     }
     async setExpire(expire:number,autoRenew?:boolean){
     async setExpire(expire:number,autoRenew?:boolean){
@@ -48,6 +52,13 @@ class SessionManager{
     public static _storageType = 'file';   //默认以文件形式存储
     public static _storageType = 'file';   //默认以文件形式存储
     public static _storageInstance:RedisClientType|undefined;
     public static _storageInstance:RedisClientType|undefined;
 
 
+    public static async check(sessionKey:string){
+        if(SessionManager._storageType=='redis' && SessionManager._storageInstance){
+            const ret = await SessionManager._storageInstance.exists(sessionKey);
+            if(ret==1) return true;
+            return false;
+        }
+    }
     public static async set(sessionKey:string,key:string,value:any|null){
     public static async set(sessionKey:string,key:string,value:any|null){
         if(SessionManager._storageType=='redis' && SessionManager._storageInstance){
         if(SessionManager._storageType=='redis' && SessionManager._storageInstance){
             let ret;
             let ret;

+ 2 - 0
source/system/module/mvc/mvc.ts

@@ -73,6 +73,7 @@ class MVC {
         const requestData:RequestData = {
         const requestData:RequestData = {
             req,res,
             req,res,
             path:'' as string|null,
             path:'' as string|null,
+            refer:URL.parse(req.headers.referer||''),
             method:req.method?.toLowerCase()||'get',
             method:req.method?.toLowerCase()||'get',
             COOKIE:{} as any,
             COOKIE:{} as any,
             GET:{},
             GET:{},
@@ -80,6 +81,7 @@ class MVC {
             UPLOAD:{},
             UPLOAD:{},
             SESSION:{} as any
             SESSION:{} as any
         }
         }
+        // if(requestData.path==URL.parse(req.headers.referer as string,true).pathname) return;
         req.headers.cookie && req.headers.cookie.split(';').forEach((Cookie)=>{
         req.headers.cookie && req.headers.cookie.split(';').forEach((Cookie)=>{
             const parts:Array<string> = Cookie.split('=');
             const parts:Array<string> = Cookie.split('=');
             let key = parts.shift();
             let key = parts.shift();