How to do AOP with node.js?

前端 未结 3 1240
独厮守ぢ
独厮守ぢ 2021-02-09 06:01

I have a little problem doing some AOP with node.js: Let\'s say I have an application in a script called server.js, and I want to monitor its functions.

Here is

3条回答
  •  我寻月下人不归
    2021-02-09 06:44

    I think it is due to the nature of the Javascript language - implies a lot of code intrusion.

    please don't :'(

    AOP is an extension of OOP, there is no AOP without OOP.

    I suggest you to use kaop or TS version with ES7 decorators kaop-ts

    1º: npm install kaop --save

    2º: define an advice to monitor your methods:

    import { reflect } from "kaop"
    
    const Log = reflect.advice(meta => {
      //meta.args contains the arguments {array}
       console.log(meta.methodName + " called");
       console.log("with arguments: " + meta.args);
       console.log("returned: " + meta.result);
    })
    

    3º you have to organize your code following OOP guidelines:

    const Controller = createClass({
      constructor: function(app){
        app.get('/', this.home);
        app.get('/login', this.login);
        app.use(this.notFound);
      },
      login: [function(req, res){
        //what ever
      }, Log],
      home: [function(req, res){
        res.setHeader('Content-Type', 'text/plain');
        res.end('Home');
      }, Log],
      notFound: [function(req, res){
        res.setHeader('Content-Type', 'text/plain');
        res.send(404, 'Page introuvable !');
      }, Log]
    })
    

    I've writed an article on 2018 which discuss AOP on JS server side.

提交回复
热议问题