我的 Node.js 应用程序提供了 WebSockets 和 RESTful接口。我写了一个小替代品Backbone.synch
来使用 Socket.IO 作为传输。
DRY 问题:在客户端事件上执行的回调包含与 RESTul 路径的回调几乎相同的逻辑。客户端发出的事件和数据之间的示例映射,以及相应的操作:
+----------------+---------------------------------+--------------------+
| event emitted | data emitted | RESTful URL |
+----------------+---------------------------------+--------------------+
| read:users | empty string | GET /users |
| read:users | id of the model | GET /users/:id |
| create:users | full model as JSON | POST /users |
| destroy:users | id of the model | DELETE /users/:id |
| update:users | full model as JSON (with id) | PUT /users/:id |
| patch:users | partial model as JSON (with id) | PUT /users/:id |
+----------------+---------------------------------+--------------------+
示例(99% 的重复逻辑/代码):
var UserModel = require('./models/user'); // Mongoose model
// Express path
app.get('/users/:id?', function (req, res)) {
var query = !id ? {} : { _id: id };
UserModel.find(query, function (err, doc) {
return err ? res.send(404, null) : res.send(200, doc);
});
};
// SocketIO listening to the read:users event
socket.on('read:users', function(id, cb) {
var query = !id ? {} : { _id: id }
UserModel.find(query, function (err, doc) {
return err ? cb(err.message, null) : cb(null, doc);
});
});
因为我玩了几天 Node.JS 和事件编程(和 JavaScript),所以我正在寻找一个关于如何设计“控制器”的好建议,比如可以轻松处理重复代码的通用对象。谢谢。