我应该在哪里写模型或控制器查询(续集)?
我试图找出我应该在节点js应用程序中使用sequalize作为ORM编写查询的位置。
例如,我有一个模型地址,我写数据是这样的:
let adr = await Address.create({street, number, city, state, country})
我应该将这些代码写入控制器,在那里获取数据还是在模型中,然后传递给模型的方法(例如整个对象地址)? 最佳做法是什么?
我认为把它写在模型中更好,因为我可以在许多控制器中使用相同的代码。 但也许还有一些其他的限制。
其实你应该使用一个repository
。 后面的想法是创build一个将抽象数据库的模块,只需将其作为dependency injection,然后使用控制器中的存储库,一个简单的例子就可以像这样。
// repository.js module.exports = (db) => { const findUserById = (id) => { // db query your user by id } const createUser = (data) { // db insert a new user } // ... other repository functions to deal with the database return Object.create({ findUserById, createUser, // ... }) }
然后在你的控制器中,你将通过给出正确的数据库连接来使用这个版本库。
const repository = require('./repository.js')(dbConnection); app.get('/users/:id', (req, res) => { repository.findUserById(req.params.id); // ... })
通过这种方式,您可以轻松地通过模拟数据库来testing您的代码,甚至可以使用良好的值进行testing。 而你抽象你的数据库连接和其他重要的function,例如,你将需要改变你的数据库从mysql
到mongodb
你将只更改存储库,而不是整个应用程序或控制器。
所以一个好的做法是使用存储库进行sequelize
也存在一种方法来做到这一点。
var db = require('../models'); var UsersRepository = { findByEmail: function(email) { return db.User.findAll({ where: { email: email } }) } } module.exports = UsersRepository;