Jav*_*lez 10 javascript node.js restify
上下文
我正在尝试使用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]
}
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
在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 :(
*/
Run Code Online (Sandbox Code Playgroud)
在第一次安装中,handler在通过path和加入资源时执行verb.正确履行卸载请求,因为访问Resource not found时path会获得一条消息verb.然而,当第二个在服务器中安装相同的主体Resource not found时,path在加入时返回a verb.
我认为错误在[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);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
410 次 |
| 最近记录: |