koajs / discussions

KoaJS Discussions
2 stars 2 forks source link

Why Koa ctx.body not working in if statement? #12

Open danyl5 opened 4 years ago

danyl5 commented 4 years ago

I am trying to create a post RestApi in node with koa and postgresql. I have a unique email validation and want to check if email exists the it should display message user already exists with this email. My query is working but that ctx.body not working. This api is creating new user every time. It should display msg "User already exists with this email" when email exists in db. Why my ctx.body not working?

router.post('/createNewUser', async (ctx) => {

    var name = ctx.request.body.name;
    var email = ctx.request.body.email;
    var password = ctx.request.body.password;

    if (
        !name ||
        !email ||
        !password
    ) {
        ctx.response.status = 400;
        ctx.body = {
            status: 'error',
            message: 'Please fill all the fields'
        }
    } else {

        await ctx.app.pool.query("SELECT * FROM users WHERE email = $1",
                [`${email}`],
            (err, result) => {
            if(result.rows.length > 0){
                ctx.body = {
                    exceptions: "",
                    status: 200,
                    error: false,
                    message: "user already exists with this email",
                };
            }
        });

        await ctx.app.pool.query(`INSERT INTO USERS (name,email,password) VALUES ('${name}','${email}','${bcrypt.hashSync(password, 10)}')`);
        const {rows} = await ctx.app.pool.query("SELECT * FROM users ORDER BY id DESC LIMIT 1");

        ctx.body = {
            exceptions: "",
            status: 200,
            error: false,
            message: "User registered Successfully",
            data: rows[0],
        };
    }
});
chang-zhao commented 4 years ago

Maybe it's better to ask such questions on https://stackoverflow.com/search?q=koa

PS. My advice is to add logging (to check all relevant conditions and values) to where the unexpected behavior occurs. That way you could narrow down the problem's cause.

E.g. after if(result.rows.length > 0){ you add console.log(result.rows.length), and so on.

Dronar commented 4 years ago

Setting ctx.body does not stop the function, like return would do. What's probably happening is that you set ctx.body to be "user already exists", then later it will be overwritten with "user registered successfully".

mendoanjoe commented 4 years ago

try to add return ?

ctx.body = {
  exceptions: "",
  status: 200,
  error: false,
  message: "user already exists with this email",
};
return;