我想出了一种方法来做到这一点,尽管我确信有更好的选择:
1) 创建模块来处理端点上的某些操作。这些模块将需要集成到中央路由器模块中。示例stuff.js
:
exports.list = function(req, res, next) {
// Code to handle a GET request to /stuff
};
exports.create = function(req, res, next) {
// Code to handle a POST request to /stuff
};
exports.show = function(req, res, next) {
// Code to handle a GET request to /stuff/:id
};
exports.update = function(req, res, next) {
// Code to handle a PUT request to /stuff/:id
};
exports.destroy = function(req, res, next) {
// Code to handle a DELETE request to /stuff/:id
};
2)在路由器模块中定义动作的映射-> http动词:
var actions = {
list: 'get',
create: 'post',
show: 'get',
update: 'put',
destroy: 'del'
}
3)创建一个表示数据结构的对象,如下所示:
var schema = {
stuff: {
_actions: require('./stuff'),
points: {
_actions: require('./points'),
colors: {
_actions: require('./colors'),
shinyThings: {_actions: require('./shinyThings')},
dullThings: {_actions: require('./dullThings')}
}
},
ships: {
_actions: require('./ships'),
enterprises: {_actions: require('./enterprises')},
starDestroyers: {_actions: require('./starDestroyers')}
}
},
things: {_actions: require('./things')},
}
4) 在路由器初始化期间,应用程序向它传递一个 Restify 服务器对象以附加路由。在初始化期间,递归函数遍历模式对象,当_actions
找到键时,它调用第二个函数,将给定路径上的路由处理程序附加到给定服务器对象:
(function addPathHandlers(object, path) {
for (var key in object) {
if (key === '_actions') addActions(object, path);
else if (typeof object[key] === 'object') {
var single = en.singularize(path.split('/').pop());
if (path.charAt(path.length - 1) !== '/') {
path += ['/:', single, '_id/'].join('');
}
addPathHandlers(object[key], path + key);
}
}
})(schema, '/');
function addActions(object, path) {
// Actions that require a specific resource id
var individualActions = ['show', 'update', 'destroy'];
for (var action in object._actions) {
var verb = actions[action];
if (verb) {
var reqPath = path;
if (individualActions.indexOf(action) !== -1) reqPath += '/:id';
server[verb](reqPath, object._actions[action]);
}
}
}
注意:这使用了lingo模块(即 en.singularize() 函数)。由于我删除了功能的非关键部分,因此它也有点简化,但它应该是功能齐全的。
对此的灵感来自于查看 express-resource 的操作方式,尽管它没有那么精致和简单易用。