4. Updating our TrackAPI data source

📺 numberOfViews++

How are we going to update the number of views for a track? To discover that, let's visit our REST API documentation!

First let's observe the response we get when executing the GET track/:id endpoint with the ID c_0. With a successful response, we receive the track and we can see the current number of views. The number you see will depend on how many other people have completed this course recently!

To increment the number of views, we'll look at the PATCH track/:id/numberOfViews endpoint, which updates the number of views for a track.

Let's try out this endpoint and give it the same track ID c_0. When we execute this call, we get a 200 successful response and the modified track back. We can see that the number of views increased! If we run it again, we can see that the number increases again.

Note that because the API is public, you might not see the number of views go up exactly by 1. Other people might be playing around with the API like we're doing right now. But we know that from the 200 response code that we were able to increase this number.

Screenshot of REST API PATCH endpoint with 200 successful response


If we scroll down, we can also see that there is a possibility of an unsuccessful response. Let's test this out by providing a silly ID we're sure won't exist, like DOESNTEXIST.

When we execute this call, we get the expected response of 404 Error: Not Found. We'll take a look at how to handle this later on.

Screnshot of REST API PATCH endpoint with 404 error

📈 Updating the data source

Now that we know which endpoint to call and how, let's add a new method to our data source!

Remember our old friend RESTDataSource from Lift-off II? We used it to create our own TrackAPI.

Why do we use a separate RESTDataSource class to handle data retrieval?

We can find the TrackAPI data source in the server/src/datasources folder, in the track-api.js file.

In this file, we'll add a new method to our TrackAPI class called incrementTrackViews.

incrementTrackViews(trackId) {
return this.patch(`track/${trackId}/numberOfViews`);

This method takes in a trackId parameter. Inside, we need to make an HTTP PATCH request, which we can do by callingthis.patch. This method is provided to us by the RESTDataSource class we inherited from.
Inside the parentheses, we give it the endpoint, which is track/, followed by the trackId, followed by /numberOfViews. Finally, we return the result of the call.

This data source is now prepared to make the REST API call that the resolver needs. Let's set that up next!