Encountered a TypeError: Cannot read property 'ghNewPrMethod' of undefined
Every time I attempt to send a webhook POST to my Typescript application, the error mentioned above pops up.
Here is the snippet of code from the controller:
import { GhStatusSchema } from '../models/gh-status.model';
import { Request, Response } from 'express';
import * as crypto from 'crypto';
import { Helpers } from '../helpers';
import { GhNewPrMethod } from '../methods/gh-new-pr.method';
import { GitHubConfig } from '../../config/github';
const secret: string = GitHubConfig.secret;
export class GhNewPrController {
public helpers: Helpers = new Helpers();
public ghNewPrMethod = new GhNewPrMethod();
public post(req: Request, res: Response) {
console.log(111);
this.ghNewPrMethod.slackMessage(req.body, req.get('x-github-delivery'))
}
}
it appears that there is an issue with this.ghNewPrMethod.slackMess
and it seems like this
is not defined properly.
** gh-new-pr.method.ts**
import * as Slack from 'slack-node';
import { GhMessageSchema } from '../models/gh-new-pr.model';
import { SlackConfig } from '../../config/slack';
import { UsersConfig } from '../../config/users';
import { Helpers } from '../helpers';
export class GhNewPrMethod {
helpers: Helpers = new Helpers();
public findSavedPR(id) {
return new Promise((resolve, reject) => {
GhMessageSchema.find({
pull_request: id
}, (err, message) => {
if (err || message.length === 0) {
reject(err);
}
resolve(message);
});
});
}
public slackMessage(payload, header) {
console.log(payload);
}
}
The reason for splitting the code into another file was to divide and conquer by breaking down the controller into smaller functions for reusability and cleaner code organization.
If anyone could provide some guidance or assistance on this matter, it would be greatly appreciated.
route.ts
import { Request, Response, NextFunction } from "express";
import { GhNewPrController } from '../controllers/gh-new-pr.controller';
export class Routes {
public ghNewPrController: GhNewPrController = new GhNewPrController()
public routes(app): void {
app.route('/github')
.post(this.ghNewPrController.post)
}
}