上下文
我正在尝试使用 restify
(2.6.2) 构建一个动态服务器,一旦服务器启动,将在其中安装和卸载服务。我意识到这可能被视为一些奇怪的事情,但它在面向 DSL
的项目的上下文中是有意义的。为了实现这个目标,我实现了以下功能:
var install = function (path, method, handler) {
var id = server[method](path, function (request, response) { // [1]
handler (request, response);
});
return id;
}
var uninstall = function (id) {
delete server.routes[id]; // [2]
}
install 函数,在由路径和方法名 [1] 指定的路由中安装处理程序。卸载函数,通过从路由 [2] 中删除处理程序来卸载它。此功能通过以下代码公开为服务:
var db = ...
var server = restify.createServer ()
.use (restify.bodyParser ({ mapParams: false }))
.use (restify.queryParser ())
.use (restify.fullResponse ());
service.post ('/services', function (request, response) {
var path = request.body.path;
var method = request.body.method;
var handler = createHandler (request.body.dsl) // off-topic
var id = install (path, method, handler)
db.save (path, method, id); // [3]
});
service.del ('/services', function (request, response) {
var path = request.body.path;
var method = request.body.method;
var id = db.load (path, method); // [4]
uninstall (id);
});
在 post 方法 [3] 中,从 body 中获取一个处理程序(它是如何进行的,这是题外话),并安装了一个服务,将返回的 id 存储在数据库中。 del 方法 [4] 从数据库中检索 id 并调用卸载函数。
问题
此代码已经过单元测试,并且可以正常工作,但是当我尝试执行如下所示的安装/卸载序列时出现故障。在这个例子中,请假设所有请求的主体包含相同的path
、http verb
和正确的内容来构建一个正确的handler
:
/*
post: /services : Installed -> ok
del: /services : Resource not found -> ok
post: /services : Resource not found -> Error :(
*/
在第一次安装中,当通过path
和verb
访问资源时执行handler
。卸载请求正确完成,因为在 verb
上访问 path
时获得了 Resource not found
消息。然而,当在服务器中第二次安装相同的主体时,当在 verb
上加入 path
时会返回 Resource not found
。
我认为错误在 [2] 中,因为我可能没有为 restify
使用正确的注销策略。
问题
服务器启动后,如何有效地从 restify
中删除处理程序?
最佳答案
查看 restify 源代码后,我发现了以下内容,您可能想尝试一下,而不是简单地“删除”(https://github.com/restify/node-restify/blob/master/lib/server.js)。
/*
* Removes a route from the server.
* You pass in the route 'blob' you got from a mount call.
* @public
* @function rm
* @throws {TypeError} on bad input.
* @param {String} route the route name.
* @returns {Boolean} true if route was removed, false if not.
*/
Server.prototype.rm = function rm(route) {
var r = this.router.unmount(route);
if (r && this.routes[r]) {
delete this.routes[r];
}
return (r);
};
关于javascript - 在 restify 中动态删除处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30836848/