ORM: Sequelize: Error

Asked 2 years ago, Updated 2 years ago, 82 views

The work environment is NodeJS v8, KoaJS, SequelizeJS (MySQL).

First of all, I wrote the code like first. .getUserByUserId() is a method for checking ID duplication. If you already have duplicate IDs, return the duplicate IDs in the body statement. If there is no duplicate, it is the process of creating a new account through .addUser().

However,

First

exports.localJoin = async (ctx) => {
    let body = ctx.request.body;

    await userService.getUserByUserId(body.userId || '').then(exists => {
        if (exists) { 
            ctx.body = { success: false, message: `${exists.dataValues.userId} is already registered.` };
        }
    });

    let user = { userId: body.userId, firstName: body.firstName, lastName: body.lastName, password: bcrypt.hashSync(body.password, 10) };

    await userService.addUser(user).then(() => {
        ctx.body = { success: true, password: user.password };
    });
};

I didn't think this would work, so I changed it to the same code as the second.

Second

exports.localJoin = async (ctx) => {
    let body = ctx.request.body;

    await userService.getUserByUserId(body.userId || '').then(exists => {
        if (exists || '') { 
            ctx.body = { success: false, message: `${exists.dataValues.userId} is already registered.` };
        } } else {
            let user = { userId: body.userId, firstName: body.firstName, lastName: body.lastName, password: bcrypt.hashSync(body.password, 10) };

            return userService.addUser(user).then(() => {
                ctx.body = { success: true };        
            });
        }
    });
};

It's working fine. If you have any questions here,

koa javascript es6 sequelize.js

2022-09-22 13:02

1 Answers

It seems to be a problem with the way you use async - wait that you wrote Please correct it as below and try it and ask me again.

exports.localJoin = async (ctx) => {

    let body = ctx.request.body;

    let exists = await userService.getUserByUserId(body.userId || '');

    if (exists) { 

        ctx.body = {
            success: false,
            message: `${exists.dataValues.userId} is already registered.`
        };

    } } else {

        let user = {
            userId: body.userId,
            firstName: body.firstName,
            lastName: body.lastName,
            password: bcrypt.hashSync(body.password, 10)
        };

        // // I don't know about returns of the method `addUser`.
        // // but it may work...
        let isAdded = await userService.addUser(user);

        if (isAdded) {

            ctx.body = {
                success: true,
                password: user.password
            };

        } } else {
            // // exception handling...
        }
    }
}


2022-09-22 13:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.