NestJs - not getting Injectable to work on subscriber

Viewed 873

Using a subscriber (db based on TypeORM) I could not find how to get access to the request (to get auth user creating the booking over Rest api)

I tried using Injectable as described in doc but doesn't seem to work here.

Thanks for help

booking.subscriber.ts

import { Inject, Injectable, Scope } from '@nestjs/common';
import { throwError } from 'rxjs';
import { Account } from 'src/accounts';
import { Room } from 'src/rooms';
import { TransactionEntity, TransactionsModule } from 'src/transactions';
import {
  EventSubscriber,
  EntitySubscriberInterface,
  InsertEvent,
  getRepository,
  LessThan,
  MoreThan,
} from 'typeorm';
import { Booking } from './booking.entity';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

@EventSubscriber()
@Injectable({ scope: Scope.REQUEST })
export class BookingsSubscriber implements EntitySubscriberInterface<Booking> {
  constructor(@Inject(REQUEST) private request: Request) {
    console.log('request', this.request) // return undefined
  }

  listenTo() {
    return Booking;
  }
}
2 Answers

this is what I use... I was nestjs newbee and my management of user auth has very much changed since and I would recommend to reconsider the logic.

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class BookingsInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();

    if (request.body) {
      request.body.user = request.user;
    }

    return next.handle();
  }
}


Related