diff --git a/src/fix_patch/patch_test.ts b/src/fix_patch/patch_test.ts new file mode 100644 index 0000000..f2e7e46 --- /dev/null +++ b/src/fix_patch/patch_test.ts @@ -0,0 +1,33 @@ +import { patchFun, patchInit } from "../patch"; + +class Path{ + @patchFun + async fun1(a:any) { + //这里执行脚本的内容,加了patchFun的函数,不允许重复执行 + console.log("这是第1个脚本里内容"); + return 12 + } + + @patchFun + async fun2(a:any) { + //这里执行脚本的内容,加了patchFun的函数,不允许重复执行 + console.log("这是第2个脚本里内容"); + return 12 + } + + async run(){ + await this.fun1(1); + await this.fun2(2); + } +} + +async function main(){ + await patchInit() + let patch = new Path(); + await patch.run(); + setInterval(() => { + console.log(new Date().format("MM-dd hh:mm:ss")); + }, 1000); + console.log("逻辑执行完成,等待退出"); +} +main(); diff --git a/src/patch.ts b/src/patch.ts new file mode 100644 index 0000000..c5b3d7a --- /dev/null +++ b/src/patch.ts @@ -0,0 +1,68 @@ +import { extendType } from "./extends"; +import { ctor } from "./global"; +import { initIORedis } from "./ioredis"; +import { initGcType } from "./jsonType"; +import { createLng } from "./lng"; +import { initMongoDB } from "./setMongodb"; +import { initRedis } from "./setRedis"; + +var path = require('path'); +var scriptName = path.basename(__filename); + +export function patchFun(target: any, key: string, descriptor: PropertyDescriptor) { + let scriptName; + try { + throw new Error(); + } catch (e) { + let caller = (e.stack.split("\n").slice(2)[0].split("\\").slice(-2)); + scriptName = caller[1].split(':')[0]; + } + + if(!scriptName){ + console.log('获取不到脚本名'); + return; + } + const originalMethod = descriptor.value; + descriptor.value = function(...args: any[]) { + //@ts-ignore + G.mongodb.collection("_patch_run_log").findOne({ fileName: scriptName, funName: key }).then(async runed=>{ + if(runed){ + console.log(`脚本${scriptName}已经执行过${key}方法,跳过`); + return (null as any); + } + + console.log(`调用了${scriptName}脚本里的${key}方法,参数为:${args}`); + const result = await originalMethod.apply(this, args); + console.log(`执行结果为:${result}`); + + //@ts-ignore + await G.mongodb.collection("_patch_run_log").insertOne({ + "fileName": scriptName, + "funName": key as any, + "ctime":Date.now(), + "res":result + }); + return (result as any); + }); + } +} + +export async function patchInit() { + await patchStart(); +} + +async function patchStart() { + //扩展框架 + extendType(); + //游戏配置提示文件 + initGcType(); + //连接mongodb + await initMongoDB(); + //连接redis + await initRedis(); + await initIORedis(); +} +// //定义全局变量 +ctor(); +//创建语言包 +createLng(); \ No newline at end of file