2

I am trying to write custom Inject decorator, so I can have access to instance of service that is being injected and pass my data there somehow. But can't reach any success. I am not sure if this is right direction and may be there are better ways to implement this idea

e.g I have Service

@Injectable()
class S3Service {
  public getBucket(){
    console.log(this.bucket);
  }
}
class MyOtherService{

  constructor(
    @InjectWithParams({bucket: 'fooBucket'})
    private readonly customS3Service: S3Service
  ){
    this. customS3Service.getBucket() // may log fooBucket
  }
}
class MyOtherOtherService{

  constructor(
    @InjectWithParams({bucket: 'barBucket'})
    private readonly customS3Service: S3Service
  ){
    this. customS3Service.getBucket() // may log barBucket
  }
}

I tried few options, like (In Nest.js, how to get a service instance inside a decorator?), but I still can't access service instance in decorator

supermishboy
  • 99
  • 11
  • Inside the constructor, you don't need to use this to access the service. Directly you can use the service name e.g. customS3Service.getBucket(); – Bilas Sarker Aug 03 '22 at 06:46
  • @BilasSarker that's not a point of question at all. I can't find a way to provide data into service. And in my case it would just print out undefined with or without this – supermishboy Aug 03 '22 at 07:45
  • I know this is an old question, however if you haven't solved this and are willing to change any compromise you accepted, this may help you: https://github.com/nestjs/mongoose/blob/382536865f376ddc78dd919c7dd9a768d7f4ddfb/lib/common/mongoose.decorators.ts#L6 - It looks like you want something _very_ much like how @nestjs/mongoose works with @InjectConnection() – Ash Aug 01 '23 at 10:19

1 Answers1

0

I suggest you to do this

class MyOtherOtherService{

   constructor(
     @InjectWithParams({bucket: 'barBucket'})
     private readonly customS3Service: S3Service
   ){
     customS3Service.getBucket() // may log barBucket
   }
}

because you call it on your constructor you must remove 'this.'