How to return something else after takeUntil in a nestjs interceptor

Viewed 180

I'd like to return a different status code after the request close event inside an interceptor. Right now the following code will return status 200. Where should I throw an exception in this case?

import { fromEvent, Observable } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Injectable()
export class RequestCloseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    return next.handle().pipe(takeUntil(fromEvent(request, 'close')));
  }
}

Thanks in advance!

1 Answers

It appears you can change the status code by calling status() on the HttpResponseContext

import { fromEvent, Observable } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Injectable()
export class RequestCloseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const response = context.switchToHttp().getResponse().status(201); // or any code you like
    return next.handle().pipe(takeUntil(fromEvent(request, 'close')));
  }
}

I'm unable to find documentation for this, but here is a related PR:

https://github.com/nestjs/nest/pull/1901/commits/922bbc3e574ebb7694514baa097e54913dceaf99#

Related