How to do AOP with node.js?

前端 未结 3 1227
独厮守ぢ
独厮守ぢ 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:41

    To avoid reinventing the wheel, you could use nestjs which is a framework that propose a lot of tools. Among them you'll find interceptors which do what you want (i think).

    https://nestjs.com/

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-09 07:05

    A naive attempt would look something like this.

    var before = function(object, functionName, action) {
      var oldFunction = object.functionName;
      var newFunction = function() {
        action();
        oldFunction();
      };
      object.functionName = oldFunction;
    }
    
    var after = function(object, functionName, action) {
      var fn = object.functionName;
      var after = function() {
        fn();
        action();
      };
      object.functionName = oldFunction;
    }
    

    JS is very flexible; you could easily improve on this by storing the after and before actions and adding/removing them as required, but at the very least this should do what you want (albeit not in a very good manner).

    0 讨论(0)
提交回复
热议问题