问题描述
我的首要目标是避免重复自己。我正在创建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 部分。
在文档中,他们给出了an example,这意味着我什至不需要使用@inject
关键字,但这对我来说没有意义。最终,我必须在该构造函数中添加一些内容,不是吗?当我终于走到new IssueController('/path',[@inject db something here])
时,是否不需要在@inject
所在的地方放东西?
我的问题
- 在基类和子类中都需要使用@inject吗?
- 我需要致电
new
时插入什么?
最终,看来我做错了。你能指出我正确的方向吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)