使用带有Express控制器基础和子类的InversifyJs进行依赖注入 我的问题

问题描述

我的首要目标是避免重复自己。我正在创建Node.js Express服务器。我想创建几个类控制器,每个类都有自己的路由,并且都具有完全相同的CRUD功能获取单个记录,获取所有记录,更新单个记录,删除记录,为其中的每个数据对象发布新记录。我的数据库,但我希望能够扩展这些控制器以在这些控制器之上添加其他功能

我的第二个目标是使用依赖注入在这些控制器中使用数据库服务。

问题是,当我将其注入基类构造函数中时,TypeScript编译器会感到不安。现在它要我将其添加到子类构造函数中,


// THE BASE CLASS
import { inject } from "inversify";
import db from "../db";

export default class Controller {

    protected _db: db;
    public path: string;
    public router = Router();

    constructor(path: string,@inject(db) databbase: db) {
        this._db = databbase;
        this.path = path; // path for my special record
        this.initializeRoutes();
    }

    public initializeRoutes(): void {
        this.router.get(this.path + '/:id',this.getRecordById);
    }

    getRecordById = async (req: Request,res: Response): Promise<boolean>  => {
        const { rows } = await this._db.query('SELECT * FROM issues WHERE id = $1',[req.params.id]);
      
        res.send(rows.pop());
        return Promise.resolve(true);
    }
}
// THE SUBCLASS
import { inject } from "inversify";
import db from "../db";
import Controller from "./Controller";


export default class SubController extends Controller {

    constructor(path: string,@inject(db) _db: db) { // <-- Do I have to inject it here,as well?
        super(path,_db);
    }

    // I will add additional methods here,unique to my SubController

}

然后,当我需要使用该类时,它现在希望我填写第二个参数,即子类构造函数 db 部分。

See,now when I need to use that class it wants me to put something in the second parameter for the constructor.

在文档中,他们给出了an example,这意味着我什至不需要使用@inject关键字,但这对我来说没有意义。最终,我必须在该构造函数添加一些内容,不是吗?当我终于走到new IssueController('/path',[@inject db something here])时,是否不需要在@inject所在的地方放东西?

我的问题

  1. 在基类和子类中都需要使用@inject吗?
  2. 我需要致电new时插入什么?

最终,看来我做错了。你能指出我正确的方向吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...