[英]How to inject object into route method in Fastify using TypeScript?
我創建了以下類控制器。
class ProjectsController {
queryBus: QueryBus;
commandBus: CommandBus;
constructor(queryBus, commandBus) {
this.queryBus = queryBus;
this.commandBus = commandBus;
}
async get(req, reply) {
reply.code(200).send(await this.queryBus.execute<GetOneProjectQuery, String>(GetOneProjectQuery));
}
這是我注冊的路線。
export default async (fastify, opts, done) => {
const { commandBus, queryBus } = fastify.di;
const projectsController = new ProjectsController(queryBus, commandBus);
await fastify.get("/", await projectsController.get);
done();
};
當我提出請求時,我的this.queryBus
總是未定義的。 我不知道如何將兩個對象注入一個類,這樣我就可以在get
方法中使用它們。 當然,當我創建
await fastify.get("/", async(req, reply)=>{this.queryBus...});
它工作正常。
你能告訴我,如果有可能以面向對象的方式來做嗎?
為了解決這個問題,我使用了來自 reddit 用戶響應的代碼。
function factory(controller) {
return {
get: async (req, reply) => controller.get(req, reply),
post: async (req, reply) => controller.post(req, reply),
};
}
export default async (fastify, opts, done) => {
const { commandBus, queryBus } = fastify.di;
const projectsController = new ProjectsController(queryBus, commandBus);
await fastify.get("/", factory(projectsController).get);
done();
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.