Saturday 15 April 2017

Express - REST API - repository instance is lost during routing

please can you help me with my routing problem? I'm trying to make a REST API using typescript and repository pattern in Node.js (express).

I have two generic classes BaseRepository and BaseController which together handle the basic CRUD transactions. Other domain controllers are derived from these ones.

There is my code:

productRouter.ts used to handle routes:

import { Router } from 'express';

import { ProductController } from '../controllers/ProductController';

class ProductRouter {
    private _router: Router;
    private _controller: ProductController;

    constructor() {
        this._router = Router();
        this._controller = new ProductController;
    }

    get routes(): Router {
        this._router.get('/product', this._controller.getAll);
        this._router.post('/product', this._controller.create);
        this._router.get('/product/:id', this._controller.getById);
        this._router.put('/product/:id', this._controller.update);
        this._router.delete('/product/:id', this._controller.delete);
        return this._router;
    }
}

productController.ts used to init the BaseRepository and its derived from the BaseController.

import { BaseController } from '../common/BaseController';
import { BaseRepository, IRepository } from '../common/BaseRepository';

import { Product, IProduct } from '../models/Product';

export class ProductController extends BaseController<IProduct> {

    constructor() {
        const productRepository = new BaseRepository<IProduct>(Product);
        super(productRepository);
    }
}

BaseController.ts

export class BaseController<T> implements IController {
    private _repository: IRepository<T>;

    constructor(repository: IRepository<T>) {
        this._repository = repository;
    }
    getAll(req: Request, res: Response, next: NextFunction): void {
        this._repository.getAll((err, result) => {
            if (err)
                res.send(err);

            res.json(result);
        });
    }

Every time I navigate to appropriate route I get the following error:

TypeError: Cannot read property '_repository' of undefined
    at BaseController.getAll (C:\Users\vrbat\Documents\Projects\router-test\src\api\common\BaseController.ts:19:13)
    enter code here

I don't know why, because the _repository property is iniciated in productController.ts.



via jezikk

No comments:

Post a Comment