3
I’m studying the library (Express) and the language (Javascript), but this type of repetition below ends up bothering me and. I wonder what you would do in the situation to reduce the repetition of code.
This is a middleware I’m making for a route and, if you notice, there’s a section where I check the username
, password
, email
, fullName
and birthDate
, that return exactly the same thing, but with the name of the model changed. I ended up spending 5 lines to do this.
The question is: Is there any way to reduce this repetition of code?
module.exports = {
register: async (req, res) => {
const {
username,
password,
email,
fullName,
birthDate
} = req.body
if (!username) return res.json({error: 'Username not found.'})
if (!password) return res.json({error: 'Password not found.'})
if (!email) return res.json({error: 'Email not found.'})
if (!fullName) return res.json({error: 'Full name not found.'})
if (!birthDate) return res.json({error: 'Birthdate not found.'})
const userEmailExists = await userService.fetch( { email } ) ? true : false
const userNameExists = await userService.fetch( { username } ) ? true : false
if (userEmailExists) return res.json({error: 'User email already exists.'})
if (userNameExists) return res.json({error: 'Username already exists.'})
const user = await userService.create({ username, password, email, fullName, birthDate })
user.password = undefined
return res.status(200).json(user)
}
}
Luiz, what sensational tips! This certainly covers my difficulty, thank you! Do you know any Patterns design material in functional programming? !
– Renan César
Nothing that has been commented here has much to do with functional programming, but an excellent reference to learn more about how Javascript works is this excellent book: "Javascript for inpatient programmers". If you want to learn functional programming (in fact), I suggest going to a more paradigm-oriented language, like Haskell. Then you go back to JS and apply the concepts you learned.
– Luiz Felipe