0

I've created the following class controller.

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));
  }

And this is my registered route.


export default async (fastify, opts, done) => {
  const { commandBus, queryBus } = fastify.di;
  const projectsController = new ProjectsController(queryBus, commandBus);
  await fastify.get("/", await projectsController.get);
  done();
};

When I make a request, my this.queryBus is always undefined. I don't know how to inject two objects into a class so then I can use them in a get method. Of course, when I create

await fastify.get("/", async(req, reply)=>{this.queryBus...});

it works correctly.

Could you tell me please, if it's possible to do it in an object-oriented way?

sobi3ch
  • 2,555
  • 2
  • 31
  • 41
mkubasz
  • 495
  • 2
  • 7
  • 16

1 Answers1

0

To solve this problem I used this code from reddit user's response.

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();
};

mkubasz
  • 495
  • 2
  • 7
  • 16