TypeDI and fastify-decorators issue (dependency injection)

30 views Asked by At

I'm running into an issue when trying to use fastify-decorators and typedi, my goal would be to have something like NestJS where we can inject dependencies like services and repositories using their interfaces, but this seems to be difficult with fastify.

The error I receive is:

Cannot read properties of undefined (reading 'getSomething')

And here is the code:

UserController.ts:

import { Controller, GET } from "fastify-decorators";
import { Inject } from "typedi";
import { FastifyReply, FastifyRequest } from "fastify";
import { UserServiceImpl } from "@services/UserServiceImpl";

@Controller("/users")
export default class UserController {
  @Inject()
  private userService!: UserServiceImpl;

  @GET("/")
  async getUser(request: FastifyRequest, reply: FastifyReply) {
    const users = await this.userService.getSomething();
    reply.send(users);
  }
}

UserServiceImpl.ts:

import { Controller, GET } from "fastify-decorators";
import { Inject } from "typedi";
import { FastifyReply, FastifyRequest } from "fastify";
import { UserServiceImpl } from "@services/UserServiceImpl";

@Controller("/users")
export default class UserController {
  @Inject()
  private userService!: UserServiceImpl;

  @GET("/")
  async getUser(request: FastifyRequest, reply: FastifyReply) {
    const users = await this.userService.getSomething();
    reply.send(users);
  }
}

app.ts:

import Fastify, { FastifyBaseLogger } from "fastify";
import { bootstrap } from "fastify-decorators";
import { resolve } from "path";
import logger from "@config/logger";
import { useContainer } from "@fastify-decorators/typedi";
import { Container } from "typedi";

export default function buildApp() {
  const app = Fastify({
    logger: logger as FastifyBaseLogger,
  });

  useContainer(Container);

  app.register(bootstrap, {
    directory: resolve(__dirname, "controllers"),
    mask: /Controller\.ts$/,
  });

  return app;
}

index.ts

import "reflect-metadata";
import { PORT } from "@config/env";
import buildApp from "./app";

const start = async () => {
  const app = buildApp();

  try {
    await app.listen({
      port: PORT,
      host: "0.0.0.0",
    });
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
};

start();

And below in the image is my folder structure: enter image description here

what could be wrong?

0

There are 0 answers