I’m working on an Express.js that uses Sequelize as the ORM, my Character model is declared like this on models/character_model.js:
class Character extends Sequelize.Model{
//fields and stuff
}
And I have model creation code that I put directly in the controller:
async create (req, res) {
await models.Character.findOrCreate({
where: { name: req.body.name },
defaults: {
//some fields
}
})
//other code
return res.status(200).json(data)
}
This seems ok to me at least, seems like the kind of code that should be in the controller, right?
But then I do this
const { Op } = require('sequelize')
async search (req, res) {
let character = await models.Character.findOne({
where: {
name: { [Op.iLike]: `%${req.params.name}%` }
}
})
//other code
return res.status(200).json(data)
}
And that to me seems like code that should be somewhere else, it’s not separating the concerns very well in my opinion, I don’t think I should have that much database logic in the same place where I put endpoint responses. Also, I’m importing stuff from sequelize here and in models, instead of having all of it contained in one file.
What do you think? Should I put that findOne call somewhere else? Maybe a separate file (a utils file or something, or maybe some character_manager.js file in the models folder), or make a method inside the Character class, or maybe in the same file, but as a different export.
And if I’m putting that code somewhere else, maybe I should do the same for the findOrCreate call as well, right? That way the controller doesn’t do any sequelize logic.
I really need to follow the best practices for this project.