Search code examples
node.jstypescriptkoakoa2

Koa(nodejs)/TS Controller, Error: cannot read x of undefined


I have typescript in the back and have an email controller, that email controller is a class and then does various stuff, passing data to the class works, but, not when trying to initialize another class.

email.router.ts

import Router from 'koa-router';
const router = new Router();
import { Email } from '../Controllers/sendEmail.controller';
const email = new Email();
console.log('email class', email); // all data there

router.post('/resetPassword', email.resetPassword);

export default router.routes();

Email Class

export class Email {
  public conn: any = new Connection(); // all data there

  public constructor() {
    this.conn = this.conn;
    console.log('in constructor of email', this.conn); // all data there
  }

  public async resetPassword(ctx: Context): Promise<void> {
    console.log('email -->', ctx.request.body); // passed by reference correctly
    console.log('conn -->', this.conn); // error*
  }
}

Connection Class

export class Connection {
  public smtpHost = 'host';
  public smtpPort = 1231273612;
  public smtpSecure = boolean;
  public smtpUser = '[email protected]';
  public smtpPass = 'someSuperSecretPassword';

  public token: string;

  public constructor(token?: string) {
    this.token = token;
  }

  public message(): string {
    return (
      `string with ${this.token}`
  }
}

error* TypeError: Cannot read property 'conn' of undefined

I for the life of me am struggling with this.... here is a stack blitz


Solution

  • You need to bind the this parameter. Either:

    router.post('/resetPassword', ctx => email.resetPassword(ctx));
    

    or:

    router.post('/resetPassword', email.resetPassword.bind(email));