Monday, 10 April 2017

Property in class is undefined when used in class method

Writing a test REST api with NodeJs for learning purposes. Currently I only have 1 route which accepts a parameter (which works fine).

I'm using an express router to route the GET request to my controller. All of the routing is working as expected.

My ServiceController currently has a ctor function which accepts 2 parameters. Both of these parameters are passed into the ctor function by the router during instantiation.

In the ServiceController ctor I store the parameters in to fields.

The issue is, when I try to access these fields in a class method I'm getting a "TypeError: Cannot read property 'exec' of undefined". I did write both of these values to the console to ensure that the ServiceController was receiving these values correctly (which it is).

So, i'm unsure why im getting this error when I attempt to access either "this.exec" or "this.logger" in the get method.

Router

import express from 'express';
import { exec } from 'child-process-promise';
import ServiceController from '../controllers/serviceController';

let routes = (logger) => {
const router = express.Router();
let controller = new ServiceController(exec, logger);

router.route('/status/:name')
    .get(controller.get);

return router;
};

module.exports = routes;

ServiceController

export default class ServiceController {
constructor(childProcess, logger) {
    this.logger = logger;
    this.exec = childProcess;
}
get(req, res) {
    if (!req.params.name) {
        res.status(400).send('A service name was not provided');
    } else {
        this.exec(`sc query ${req.params.name}`).then(result => {
            if (result.stderr) {
                this.logger.log.warn(`stderr: ${result.stderr}`);
            }
            const regex = /STATE\s+:\s+\d+\s+(\w+)/;
            let [, status] = result.stdout.toString().match(regex);
            if (!status) {
                throw new Error('Status query unsuccessful');
            }

            let service = {
                name: req.params.name,
                status: status
            };

            res.json(service);
            return service;

        }).catch(error => {
            this.logger.log.error(`${error.name} ${error.message}`);
            res.status(500).send('An error occurred while executing command');
        });
    }
}
}



via WBuck

No comments:

Post a Comment