Search code examples
node.jstypescriptmongooseasync-awaitkoa

Koa Endpoint always return 404


I've been running in a problem where I believe a call is returning too early and makes my response always a 404 - Not Found message. The entry is made in the database, so it's returning early from what I can tell. I think I've awaited the correct parts, but clearly that is not the case. I've also tried awaiting on the db.AddUser as well, with no luck there.

Endpoint

//Post signup
public async SignUpAsync(ctx: Context) {
    try {
        let code = await SignUpVerification.GenerateCode();
        let user = await this.InfoFromRequest(ctx.request.body);
        user.Code = code;
        await db.AddUser(user);
        console.log('added db user');
        //await SignUpVerification.SendVerificationText(user.PhoneNumber, code)
        console.log('success message');
        ctx.body = 'Success';
    } catch (err) {
        ctx.status = 400;
        ctx.body = err;
    }
};

private async InfoFromRequest(requestBody: any) {
    return {
        Email: requestBody['email'],
        FirstName: requestBody['firstname'],
        MiddleName: requestBody['middlename'],
        LastName: requestBody['lastname'],
        Pwd: requestBody['pwd'],
        PhoneNumber: requestBody['phonenumber']
    } as IUserModel;
}

Call to the model

async AddUser(newUser: IUserModel) {
    return await userModel.AddUser(newUser);
}

Model call

async AddUser(newUser: IUserModel) {
    try {
        var userToSave = new User({
            name: {
                firstname: newUser.FirstName,
                middlename: newUser.MiddleName,
                lastname: newUser.LastName
            },
            email: newUser.Email,
            pwd: newUser.Pwd,
            code: newUser.Code,
            phonenumber: newUser.PhoneNumber
        });

        let result = await userToSave.save();
        console.log('New User saved');
        console.log(result);
    } catch (err) {
        throw new Error(err);
    }
}

Method generates code that is returned from Model Call

static async GenerateCode() {
    return await (Math.floor(Math.random() * 90000) + 10000).toString();
}

Solution

  • Evert was onto the right track with looking at how the function was added in the middleware.

    Before

    this.router.post(
                'login/',
                (ctx) => {
                    this.controller.LoginAsync(ctx);
                }
            );
    

    Correct

    this.router.post(
                'login/',
                async (ctx) => {
                    await this.controller.LoginAsync(ctx);
                }
            );