我在用 node.js 做一些 AOP 时遇到了一点问题: 假设我在名为 server.js 的脚本中有一个应用程序,我想监视它的功能。
代码如下:
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.setHeader('Content-Type', 'text/plain');
res.end('Home');
});
app.get('/login', function(req, res){
login(req,res);
module.exports.login_(req, res);
});
app.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.send(404, 'Page introuvable !');
});
function login(req, res){
res.setHeader('Content-Type', 'text/plain');
res.end('Page de login');
}
app.listen(1616);
如您所见,我想监控唯一函数login(req, res)。为了做到这一点,我想在另一个脚本中使用 AOP,但我能找到的所有东西——我认为这是由于 Javascript 语言的性质——意味着很多代码入侵。
有没有办法像在 Spring/Java 中那样做 AOP?无需进行任何代码入侵?
目前,我的解决方案是:
这是我们的应用程序,有一些代码入侵
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.setHeader('Content-Type', 'text/plain');
res.end('Home');
});
app.get('/login', function(req, res){
//We need to use the function in module.exports
//--> code intrusion
//login(req,res);
module.exports.login_(req, res);
});
app.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.send(404, 'Page introuvable !');
});
function login(req, res){
res.setHeader('Content-Type', 'text/plain');
res.end('Page de login');
}
//We wrap here the function we want to monitor
wrappedLogin = function(req, res){
login(req, res);
}
module.exports = {
login_ : wrappedLogin
};
app.listen(1616);
这是我们的 AOP 脚本
var aop = require("node-aop");
//Include the server
var server = require('./server.js');
aop.before(server, "login_", function(key, value){
//I do some stuff here
});
aop.after(server, "login_", function(key, value){
//I do some stuff here
});
最后,我要做的就是
node aop.js
它有效,但如您所见,存在一些代码入侵。我想摆脱它。有人知道吗?
最佳答案
I think it is due to the nature of the Javascript language - implies a lot of code intrusion.
请不要:'(
AOP是OOP的扩展,没有OOP就没有AOP。
我建议你使用kaop或带有 ES7 装饰器的 TS 版本 kaop-ts
1º: npm install kaop --save
2º:定义一个建议来监控你的方法:
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º 您必须按照 OOP 准则组织您的代码:
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]
})
我写了一个 article在 2018 年讨论 JS 服务器端的 AOP。
关于javascript - 如何用 node.js 做 AOP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24304146/