stop endpoint within a promise

Viewed 20

I want to make a watchdog (using setInterval) that checks in the background some checks during a controller's endpoint (using an interceptor for initializing and clearing the interval function).

If some of the checks are false, I want to end the handle of the endpoint. If I throw an error, it gets to UnhandledPromiseRejection. If I catch it there, the endpoint continues, and if not - the application stops.

Is there a way I can stop the endpoint through background checks?

1 Answers

Found an answer

In the interceptor, it's possible to merge handle.next() and interval, and then filter out the interval to prevent numerous calls to the next interceptor. In the rxjs interval, it's possible to throw an exception

@Injectable()
export class WatchdogInterceptor implements NestInterceptor {
  constructor(
  ) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    let shouldThrow = false;
    const heartBeatFunction = context.switchToRpc().getContext<KafkaContext>().getHeartbeat();
    const intervalId = setInterval(async () => {
        if (someCheckFails) shouldThrow = true;
    }, 1000);

    let isFinished = false;
    return merge(
      next.handle().pipe(
        tap(() => {
          isFinished = true;
          clearInterval(intervalId);
        }),
        catchError(err => {
          isFinished = true;
          clearInterval(intervalId);
          return throwError(() => err);
        })
      ),
      interval(1000).pipe(
        takeWhile(() => !isFinished),
        filter(() => {
          if (shouldThrow) {
            throw new Error();
          }
          return false;
        })
      )
    );
  }
}

Related