needle-innovision / nestjs-tenancy

Multi-tenancy approach for nestjs - currently supported only for mongodb with mongoose
MIT License
187 stars 58 forks source link

Triggering events with `EventEmitter2` triggers `getTenantFromRequest` with Event object #46

Open stichiboi opened 1 year ago

stichiboi commented 1 year ago

I did the README setup to implement multi-tenancy in my API.

Testing my endpoint, I was getting this error

            tenantId = req.get(`${tenantIdentifier}`) || '';

TypeError: req.get is not a function
 at Function.getTenantFromRequest

It was weird because my service was correctly returning the HTTP response and it was creating the document

    return this.jobModel.create(document).then(doc => {
      this.eventEmitter.emit(
        "job.created",
        new JobCreatedEvent(apiKey, doc._id),
      );
      return doc._id;
    });

Setting a breakpoint at tenancy-core.module.js:130:28 I took a look at the object being passed This is what I found: instead of the request object, it was taking the event I just created image

(To be clear: the breakpoint activated normally during the request. But it also triggered after I fired the event which should not have happened) How can I solve this?

sandeepsuvit commented 1 year ago

Hi @stichiboi thanks for writing in. This library mostly relies on request scoped object and get triggered via that context. Since you mentioned it also triggered during an event tigger, this has to be inspected. Can you create a minimal representation of your above said issue in an example project and share me the link so that i can investigate further.

stichiboi commented 1 year ago

Here you go https://github.com/stichiboi/nestjs-tenancy-eventemitter-trigger

Just ping localhost:3000 and add the X-TENANT-ID header

Note: right now in my app.module I'm importing the TenancyModule both with forRoot and forFeature. In my real project I have them split into different modules (although the app.module is importing my job.module)

Right now I've solved it by adding a fake get() method on my event class

export class JobCreatedEvent {
  constructor(
    public readonly apiKey: string,
    public readonly job: JobDocument,
  ) {}

  get(tenantId: string) {
    return tenantId;
  }
}
kingRayhan commented 1 year ago

any update?