napfernandes
napfernandes

Reputation: 1359

NestJS - add dependencies as interface

The way we add dependencies in NestJS is by using the @Injectable annotation:

export class ConversationService {
  constructor(
    @Injectable() private userService: UserService,
    @Injectable() private cacheService: CacheService,
    @Injectable() private emailService: EmailService,
  ) {}
}

Do you know if there is a way to add dependencies like an interface of injectables? I couldn't find anything like that in the docs:

interface ConversationServiceDependencies {
  userService: UserService;
  cacheService: CacheService;
  emailService: EmailService;
}

export class ConversationService {
  constructor(
    @Injectable() private dependencies: ConversationServiceDependencies,
  ) {}
}

Thank y'all!

Upvotes: 0

Views: 282

Answers (1)

Micael Levi
Micael Levi

Reputation: 6675

the @Injectable() should be in the class. And you'll have to define some token in @Inject(), like so:

@Injectable() // not needed in this case
export class ConversationService {
  constructor(
    @Inject('ConversationServiceDependencies') private dependencies: ConversationServiceDependencies,
  ) {}
}

because interfaces didn't exists at runtime (a typescript thing).

and then you'll need to define what's the value of that provider at your nestjs module. This is covered in the docs btw.

Or you could use this lib: nestjs-injectable

Upvotes: 1

Related Questions