我使用Laravel开发了一个系统,现在我想将同一个系统迁移到NodeJS。在Laravel我使用的是存储库模式(this library),所以我有这个方案:
routes => controller => service => repository => (雄辩)模型
好吧,我见过一些可以帮助我完成任务的库(awilix,sequelize),但我有些疑惑。
我用这种方式构建文件夹:
/server.js
/lib/config
/lib/routes
/lib/controllers
/lib/models
/lib/services
如果我正在构建一个巨大的应用程序(系统将拥有超过100个实体),我想要一些见解。
其他问题,我没有通过awilix使用Dependency Injection,所以我尝试了一些手动,但每次我使用DepartmentController就像一个类,我得到了这个错误:
Route.get() requires a callback function but got a [object Undefined]
server.js
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
const routes = require('./lib/routes/index'); // Rotas
app.use('/', routes);
LIB /控制器/ index.js
const departmentController = require('./DepartmentController');
module.exports = {
departmentController
};
LIB /控制器/ DepartmentController.js
const Department = require('../models').Department;
const DepartmentService = require('../services/DepartmentService').DepartmentService;
module.exports = class DepartmentController {
list(req, res) {
return Department
.all()
.then(data => res.status(200).send(data))
.catch(error => res.status(400).send(error));
}
}
LIB /路由/ index.js
const routes = require('express').Router();
const department_routes = require('./DepartmentRoute');
routes.use('/api', department_routes);
module.exports = routes;
LIB /路由/ DepartmentRoute.js
const router = require('express').Router();
const departmentController = require('../controllers').departmentController;
router.route('/departments').get(departmentController.list);
module.exports = router;
LIB /模型/ Department.js
var Sequelize = require('sequelize');
module.exports = (sequelize, DataTypes) => {
var Department = sequelize.define('Department',
{
// sequelize options and database fields, working fine
}
return Department;
};
LIB /服务/ DepartmentService.js
const Department = require('../models').Department;
module.exports = class DepartmentService
{
constructor({ Department }) {
this.departments = Department
}
findAll() {
return this.departments.all();
}
}
答案 0 :(得分:0)
您在此处定义类:lib / controllers / DepartmentController.js
但是该类的方法不是静态的。所以您需要创建一个实例。
您应该在lib / routes / DepartmentRoute.js中执行此操作:
const router = require('express').Router();
const DepartmentController = require('../controllers').departmentController;
const departmentController = new DepartmentController();
router.route('/departments').get(departmentController.list);
module.exports = router;