thinkjs / thinkjs

Use full ES2015+ features to develop Node.js applications, Support TypeScript.
https://thinkjs.org/
MIT License
5.31k stars 617 forks source link

thinkjs 3.x版本中如何添加全局属性? #990

Closed Tauleos closed 6 years ago

Tauleos commented 6 years ago

DESC

ENV

OS Platform: windows

Node.js Version: v8.9.0

ThinkJS Version: v3.2.4

code

global.js

try{
  Object.defineProperties(global,{
    GLog:{
      value:(target, name, descriptor)=> {
        let oldVal = descriptor.value;
        descriptor.value = async function () {
          if(!(this.http&&this.http.module&&this.http.controller&&this.http.action)){
            think.logger.error('GLog修饰符只能用于controller/action');
            return;
          }
          let getData=this.get();
          let postData=this.post();
          let action=`${this.http.module}/${this.http.controller}/${this.http.action}`;       console.log(action,getData);
          let worker=process.env.pm_id?`=>worker_${process.env.pm_id}`:'';
          if (!think.isEmpty(getData)) {
            think.logger.info(`GLog${worker}:--- ${action} ---(get)-log: `,getData);
            //console.log(`GLog:--- ${action} ---(get)-log: `,getData);
          }
          if (!think.isEmpty(postData)) {
            think.logger.info(`GLog${worker}:--- ${action} ---(post)-log: `,postData);
            //console.log(`GLog:--- ${action} ---(post)-log: `,postData);
          }
          try {
            await oldVal.apply(this);
          } catch (e) {
            if(think.isPrevent(e)){
              return;
            }
            if(e.results&&!e.results.success){
              think.logger.error(`HttpService success false ${worker}:--- ${action} ---error-log`,e);
              // this.assign({errmsg:e.results.message});
              // this.http.error = {
              //   message : e
              // };
              // return think.statusAction('error1', this.http);
            }
            if(e.statusCode){
              think.logger.error(`HttpService ${worker}:--- ${action} ---error-log`);
              //console.log(`HttpService:--- ${action} ---error-log`);
            }else{
              think.logger.error(`GLog ${worker}:--- ${action} ---error-log: `,e);
              //console.log(`GLog:--- ${action} ---error-log: `,e);
            }
            // this.assign({errmsg:e});
            return Promise.reject(e);
          }
        };
      }
    }
  });
}catch(e){
  console.error('global',e);
}

master.js

require('./global');

error message

ReferenceError: GLog is not defined
    at Object.<anonymous> (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\app\home\controller\mobileapi.js:1555:71)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at exports.interopRequire (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\node_modules\think-loader\loader\util.js:14:13)
    at files.forEach.file (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\node_modules\think-loader\loader\common.js:16:26)
    at Array.forEach (<anonymous>)
    at Object.loadFiles (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\node_modules\think-loader\loader\common.js:12:11)
    at modules.forEach.item (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\node_modules\think-loader\loader\common.js:48:40)
    at Array.forEach (<anonymous>)
    at Object.load (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\node_modules\think-loader\loader\common.js:46:15)
    at Loader.loadController (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\node_modules\think-loader\index.js:49:19)
    at thinkLoader.loadData (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\node_modules\thinkjs\lib\loader.js:45:42)
    at thinkLoader.loadAll (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\node_modules\thinkjs\lib\loader.js:110:12)
    at Application.run (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\node_modules\thinkjs\lib\application.js:204:18)
    at Object.<anonymous> (E:\suningNodejs\CLOUDFMOBILE0171130\cloudfe-mobile\www\development.js:22:10)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

more description

如上代码。我在全局注册了一个GLog的修饰符。在master和worker中引用进来,但是在controller中无法使用。是因为在加载controller的时候,我的GLog修饰符还没有定义到global全局里吗?这种情况有没有解决办法?

welefen commented 6 years ago

bootstrap 里的文件会在最后加载,具体见:https://github.com/thinkjs/thinkjs/blob/master/lib/loader.js#L108-L116 (这样设计是因为更多的需求是 bootstrap 里调用 model,controller 等)

如果要在 controller 等里面使用的话,放在 action 内部就可以了。如果非要在 class 外部引用的话就手工 require 下

Tauleos commented 6 years ago

@welefen 我这里目前是要实现如下代码的功能。用一个修饰器来统一处理action的错误,那按照您的说法,我需要在每一个controller里手工require这个修饰器的定义文件吗?

@annotation
class MyClass { }

function annotation(target) {
   target.annotated = true;
}
welefen commented 6 years ago

@macurial 你可以在 base controller 里 require 下就可以了。

Tauleos commented 6 years ago

@welefen 好的,顺便问一下,现在的路由解析没有大小写转换了吗?我从2.x版本升级到3.x版本,需要手动把之前下换线分隔的路由改成驼峰形式的才可以。

welefen commented 6 years ago

@macurial 是的,在 3.0 去掉了(因为 3.x 里去掉一些规范限制)