我是网络开发的新手,并使用node和express开发了一个Web服务器。我已经使用了MVC模式,模型是sequelizejs对象。但是,对于我的控制器,你目前很少甚至没有OOP,我想知道一些OO编写控制器的方式而不是使用匿名函数来处理请求:
app.get('/test',function(req,res){})
也许我可以使用URL和模型作为HTTP谓词的属性和方法为每条路径创建对象:
//Use test.model for interacting with model
app.get(test.URL,test.get);
app.post(test.URL,test.post);
app.put(test.URL,test.put);
app.patch(test.URL,test.patch);
app.delete(test.URL,test.delete);
但是,它看起来有点过分,因为以这种方式制作的大多数/所有控制器对象最终将成为没有继承,多态和重用的单例。
问题:是否有更好的OO方式来编写控制器?
答案 0 :(得分:15)
您可以拥有一个控制器类,其构造函数接受一个快速对象,为您设置路径。所以这是一个示例基础Controller
类:
/**
* @param connect can either be Sencha Labs' `connect` module, or
*/
function Controller(express) {
var self = this;
var name = '/' + this._name;
express.post(name, function (req, res, next) {
self._create(req, res, next);
});
express.get(name, function (req, res, next) {
self._read(req, res, next);
});
express.put(name + '/:id', function (req, res, next) {
self._update(req, res, next);
});
express.delete(name + '/:id', function (req, res, next) {
self._delete(req, res, next);
});
}
// Since there aren't any protected variables in JavaScript, use
// underscores to tell other programmers that `name` is protected. `name`
// (or, more technically, `_name`) is still accessible, but at least, if a
// team is disciplined enough, they'd know better than to access variables
// with underscores in them.
Controller.prototype._name = '';
Controller.prototype._create = function (req, res, next) {
};
Controller.prototype._read = function (req, res, next) {
};
Controller.protoype._update = function (req, res, next) {
};
Controller.prototype._delete = function (req, res, next) {
};
然后,您可以通过从Users
“类”扩展来创建Controller
控制器:
function UsersController(express) {
Controller.call(this, express);
}
// This is not the most perfect way to implement inheritance in JavaScript,
// this is one of the many ways.
UsersController.prototype = Controller.prototype;
UsersController.prototype._name = 'users'
// An example override of the base `Controller#create` method.
UsersController.prototype._create = function (req, res, next) {
db.save(req.body, function (err) {
if (err) res.send(500, err.message);
res.redirect('/');
});
};
UsersController.prototype._read = function (req, res, next) {
db.read(function (err, users) {
if (err) res.send(500, err.message);
res.send(users);
});
};
一旦您声明并定义了所有适当的控制器,您就可以开始在快递应用程序中实现它们了。
// Initialize a new instance of your controller.
var usersController = new UsersController(app);
PS:对于构造函数中的快速调用,还有另一种方法可以添加create
,read
,update
,delete
路由(以及任何其他路由) 。我一开始并不想迷惑你。
function Controller(express) {
var name = '/' + this._name;
express.post(name, this._create.bind(this));
express.get(name, this._read.bind(this));
express.put([name , ':id'].join('/'), this._update.bind(this));
express.delete([name, ':id'].join('/'), this._delete.bind(this));
};
答案 1 :(得分:1)
我在TypeScript中编写了一个简单的例子,它展示了如何为快速应用程序编写控制器,并考虑到面向对象的编程。它可以很容易地应用于ES6:
<强> Server.ts 强>
import * as express from 'express';
import {CategoryController} from 'src/view/CategoryController';
export default class Server {
public app: express.Application;
constructor() {
this.app = express();
this.app.get('/', (request, response) => response.send('Root page without OOP.'));
// Using a controller to serve a view
this.app.use('/categories', CategoryController);
}
}
<强> CategoryController.ts 强>
import {Router, Request, Response} from 'express';
const router: Router = Router();
router.get('/', (request: Request, response: Response): Response => {
const payload: { [index: string]: string[] } = {categories: ['CSS', 'HTML', 'JavaScript', 'TypeScript']};
return response.json(payload);
});
export const CategoryController: Router = router;
答案 2 :(得分:0)
不是真的答案,但我创建了一个节点模块来处理自动设置快速路线。 Dynamic-Routes
//app.js
require('dynamic-routes')(app, __dirname + '/routes/');
然后
//routes/index.js
module.exports = {
priority: 1000, //this is the `/` handler, should it should be the last route.
path: '/',
//this function gets passed the express object one time for any extra setup
init: function(app) {
app.head(function(req, res) {});
},
GET: function(req, res) {
res.end('GET ');
},
POST: function(req, res) {
res.json(req.data);
}
};
答案 3 :(得分:0)
以OOP方式组织express的一种方法是使用为此提供脚手架的现有框架。 sails.js是当今最流行的节点MVC框架,并使用express.js进行路由。