2
\$\begingroup\$

Hello I have recently started studying javascript, nodejs, and reactjs front end, and I have some questions about best practices to apply in this javascript world, I would like to ask for opinions regarding how I could improve my code.

Starting with an example I have 2 functions, with different ways of handling promises

Here I have a route to add a user

 addUsers(req,res,next) {
    try {
        const {name,email,login} = req.body;
        User.existLogin(req.body.login)
        .then(async result => {
            if(!result){
                const password = await bcrypt.hashSync(req.body.password, 10);
                User.create({ 
                    name, email, login, password }).then(result => {
                    res.status(201).json({Results: result.dataValues})
                })
            }else{
                return res.status(409).json({message: 'Login already exists'}); 
            }
        })
    } catch (error) {
        res.status(500).json({error: error})
    }
}

And here I have another function to login:

async login(req,res){
    const  user  = await User.existLogin(req.body.login);
    if (!user) { return res.status(400).json({result: 'Login is wrong '});} 
    const isPassword = await User.isPassword(user.dataValues.password, req.body.password);
    if (!isPassword) { return res.status(400).json({result: 'Password is wrong '}); } 
    const jwt = auth.signjwt(auth.payload(user));
    console.log(jwt);
    res.status(200);
    res.json(jwt);
}

Looking at this the login function seems to me to be cleaner, but I have doubts if really yours I could improve in one of two (I follow different logics to do both).

I have an auth folder, where I export functions, such as my payload, my sign, my middlware to validate my jwt, but I don't know if this is a correct decision.

const jwt = require('jsonwebtoken');
const User = require('../models/User')
const config= require('../config/dbconfig');
const moment = require('moment');

module.exports = {
    signjwt (payload) {
        return jwt.sign(payload, 
            config.secretToken
                   )
    },
    payload (usuario) {
        return {
            sub: usuario.id,
            name: usuario.nome,
            email: usuario.email,
            login: usuario.username,
            admin: true,
            iat: Math.floor(moment.now()/1000), // Timestamp de hoje
            exp: moment().add(10, 'minutes').unix() // Validade de 2 dias
        }
    },
    async auth(req,res,next){
        const token = req.header('Authorization');
        console.log(token);
        if(!token) return res.status(401).json('Unauthorized');
        try{
            const decoded = jwt.verify(token,config.secretToken);
            const user = await User.findByPk(decoded.sub);
            console.log(user);
            if(!user){
                return res.status(404).json('User not Found');
            }
            res.json(user);
            next();
        }catch(error){
            console.error(error);
            res.status(400).json('Invalid Token');
        }
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ try {} catch {} doesn't make sense in the first function as you need to use .catch() of the Promise itself (also, your function doesn't return anything because the return is inside a Promise). Conversely, the second function needs try {} catch {} because that's how async/await workflow is handled. As for "best practices" there's quite a few things to improve here depending on whose "best practices" you want to follow, but there's one universal thing: use ESLint with a popular set of rules which you like and read the usual "best practices" compilations. \$\endgroup\$ – wOxxOm Nov 19 '19 at 10:14
  • \$\begingroup\$ thansk bro u can post awnser for give vote positive ? \$\endgroup\$ – gabriel Nov 19 '19 at 13:58
  • 5
    \$\begingroup\$ Welcome to code review. The title of your question is too general and could apply to too many questions on this site. A best practice on this site is to make the title about what the code does and the code should all be from a single application. The question in the title could be part of body of the question. It might help if you looked at our help page at codereview.stackexchange.com/help/how-to-ask and codereview.stackexchange.com/help/dont-ask. \$\endgroup\$ – pacmaninbw Nov 19 '19 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.