我正在尝试为我的应用程序创建特定的路由规则。
但是,我希望这些规则基于数据库中表的内容是通用的。
这意味着有时某些路由可能会根据数据库规则在 restify 服务中插入或删除。
我一直在寻找解决方案,但找不到任何东西,这是我的代码示例:
server.put('/logging/create', function(req, res, next){
return next();
});
server.delete('/logging/delete', function(req, res, next){
return next();
});
server.post('/logging/update', function(req, res, next){
return next();
});
我想要实现的是在不重新启动 Node js 脚本的情况下动态添加/删除特定请求。我拥有的是一个包含所有规则的数组。规则的一个例子是:
{
"name":"/logging/create",
"method":"put",
"status":"active"
},
{
"name":"/logging/delete",
"method":"delete",
"status":"inactive"
},
{
"name":"/logging/update",
"method":"post",
"status":"active"
}
我唯一想要的就是动态添加/删除路由。
最佳答案
你可以查询动态数据并假设你有一个数组 -
var ruleData = .... // This is your rules array
现在,每当请求到达任何动态路由时,您都可以在 ruleData
数组中检查该路由是事件还是非事件 .如果路由是活跃的然后转发请求,如果它的不活跃然后返回一个 404 状态代码。
示例 -
server.put('/logging/create', function(req, res, next){
// checking if rule for this path exists and is active
if(ruleData.find(rule => rule.name == req.path() && rule.status == 'active') != null)
next();
else
res.send(404, {error: 'This route does not exist'});
});
关于javascript - 根据数据库结果重新定义动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42697595/