I am making a Rest API in Nodejs with Express and MongoDB. The user is allowed to invite another user to participate in a board (similar to Trello). What I want is to register a new collaborator for that board.
Collaborator Scheme:
let Colaborador = new Schema({
user:{
type: Schema.Types.ObjectId,
ref: 'User',
require: [true, "El usuario es requerido"]
},
role:{
type: Number,
require: [true, "El rol es requerido"]
},
tablero:{
type: Schema.Types.ObjectId,
ref: 'Tablero',
require: [true, "El Tablero es requerido"]
}
})
As the user knows the email of the other user who wants him to collaborate on the board, I need to obtain the ID from the email that he knows, therefore, I had thought of creating a middleware to validate the email and return the id of the new partner, as follows:
let ValidarEmail = (req, res, next)=>{
if(!req.body.email){
res.status(400).json({
ok:false,
message: "El email en necesario"
})
}
User.find({email: req.body.email})
.then(user=>{
if(!user){
res.status(404).json({
ok:false,
message: "El usuario no existe"
})
}
req.colaborator = user['_id']
next();
})
.catch(err=>{
res.status(500).json({
ok:false,
err
})
})
}
I wanted to know if it is correct to do this in a middleware or it would be correct to do it directly in the controller
It's okay to delegate each of the jobs in this case it's good, you could also create another separate middleware, which will validate if the email entered is valid you could even put the first part of your function in this other function
Then you could have another middleware that validates if the entered email exists (this one would be executed only if the one above executes
next()
)The first middleware would help you to validate the mail in any call in which you need to verify that it is indeed valid (for example in the registration and in this case in adding board) also this allows you to have each function doing a single thing.
In short, if your idea is a good one, the reason for the controller is that it only acts as a link, so the less responsibility it has, the better, since the data must already be filtered before it can send it as a response, for example.