Http Polling

Hello! Today’s post will be a quick one. I’ll show you small utility, that I created for testing HTTP long-polling based API.

Testing such APIs via curl or Postman can by really annoying. I have some frontend background, so I thought that RxJs can solve my problem in few lines, in nice declarative way.

import { catchError, map, pluck, tap, mergeMap, take, delay, filter, scan } from 'rxjs/operators';


const ERROR_MSG = "Could not fetch data. Please try again later"
const maxAttempts = 10


function checkAttempts(maxAttempts: number) {
  return (attempts: number) => {
    if (attempts > maxAttempts) {
      throw new Error("Error: max attempts");
    }
  };
}

export function httpPoll(
  httpFetcher: (number) => Observable<string>,
  predicate: (string) => boolean): Observable<string> {
  return timer(0, 1000).pipe(
      scan((acc) => ++acc, 0),
      tap(checkAttempts(maxAttempts)),
      mergeMap((attempt) => httpFetcher(attempt)),
      filter(status => predicate(status)),
      take(1),
      catchError((err) => of(ERROR_MSG))
    )
}

Additionaly for this blog post, I created example on stackblitz, so you could check how it works.