nestjs / typeorm

TypeORM module for Nest framework (node.js) 🍇
https://nestjs.com
MIT License
1.91k stars 206 forks source link

Inject ConfigService into an Entity or Subscriber #1848

Closed asijoumi closed 8 months ago

asijoumi commented 8 months ago

Is there an existing issue for this?

Current behavior

Hi,

I would like to know how can I inject the ConfigService into en Entity or Subscriber.

I tried with 2 different ways :

@Entity()
@Injectable()
export class User extends BaseEntity {
  constructor(private readonly configService: ConfigService) {
    super();
  }
}

But, configService is undefined.

The second way was to create a subscriber :

import { Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { EntitySubscriberInterface, EventSubscriber } from 'typeorm';
import { User } from '../models/entities/user';

@EventSubscriber()
export class UserSubscriber implements EntitySubscriberInterface<User> {
  @Inject(ConfigService) private readonly configService: ConfigService;

  listenTo() {
    return User;
  }

  afterLoad(entity: User) {
    console.log(this.configService);
    console.log(`AFTER ENTITY LOADED: `, entity);
  }
}

But still the same problem.

Do you now how can I access to configService ?

PS : I need configService because some secrets are provided during the startup of application.

Minimum reproduction code

No

Steps to reproduce

No response

Expected behavior

Have configService

Package version

10.0.1

NestJS version

10.0.0

Node.js version

20.5.0

In which operating systems have you tested?

Other

No response

micalevisk commented 8 months ago

those subscriber classes are managed by typeorm, not by nestjs. So there's no way to make them injectable AFIAK

maybe you could find a work around tho

asijoumi commented 8 months ago

The other way was to get the NestApplication instance (like we can do with Java Spring). Is that possible with Nest ?

micalevisk commented 8 months ago

I guess you could use the standalone mode https://docs.nestjs.com/standalone-applications

asijoumi commented 8 months ago

I actually have a Rest API working fine.

The last solution (but I didn't really approved) is a static class with the necessary variables..