Making Parallel API Requests
One of the powerful features of JavaScript is the asynchronous paradigm which makes it easy to execute multiple tasks in parallel. This can come in handy when developing Cloud Apps as we often need to call more than one API. Alma imposes a governance limitation on the number of concurrent requests each app can make per user session. And the Cloud App API helps by buffering the requests and performing only 10 REST API calls simultaneously. But we still need to make the requests and handle errors correctly. We can make use of the features of Angular and ReactJS (rxjs) to make the task relatively easy.
In this use case, we assume our application will be performing an update of many users records in parallel. Of course this pattern can be used for any types of requests. We’ll first retrieve an array of user records and then perform many REST API calls simultaneously while handling errors from Alma.
We start by following the instructions in the “Adding additional routes” tutorial to add a new component and route called “parallel”. In our parallel.component.html file, we’ll create a simple button to run our example, and then a list of our users which will be updated as we retrieve the users.
In the parallel.component.ts file, we set up a getUser
function which returns a request for a user. In the function, we use the Rest Service, and pipe the result through two operators- tap
and catchError
. The tap
operator allows us to update a counter after each request is processed, which will help us later report on progress. The catchError
operator wraps any error we get from Alma and allows processing to continue. This is important since we don’t want to stop all processing if one request fails.
Next we create a loadUsers
function to do the bulk of the work. We first retrieve a list of users from Alma with the Get User API. Then we map the list of users through the getUser
function to set up the request. We then pipe the request array into the forkJoin
function which makes the requests in parallel. The result is an array of user objects (or errors). We can then handle each response, whether it is an error or success.
As our test runs, we see the list being populated. We can also see the error handling, which in this case is a simple log to the Console.
Reporting progress
We’ve included a check box in the template which controls whether we show progress. The check box sets the mode property on the progress spinner. If the mode is set to determinate, the value is calculated via a percentComplete
property which calculates the number of processed records as a percentage of the total number of requests to be made. Then when we run the code, the progress spinner fills as the requests are processed.
Using these patterns allows us to easily make parallel API calls to Alma in a controlled way and provide a responsive experience for our users.