Handle Dynamic Requests with Path Parameters in MSW

Share this video with your friends

Social Share Links

Send Tweet

When mocking a collection of resources in Mock Service Worker, such as our movies, you will encounter requests that have dynamic parts in their URL, like /movies/:slug. In this lesson, learn how to use path parameters to describe dynamic portions of the request's URL, access those parameters, and return a different response based on their values.

Lecturer: [0:00] Our application makes a GET request to fetch movie details and provides the slug of the movie we want to fetch as a dynamic part of that request URL. In other words, we don't know the exact URL until we fetch a particular movie. Let's create a handler for this dynamic request using HTTP GET.

[0:19] We will provide the static portion of the request URL and replace the dynamic parts with path parameters. A path parameter is a part of the request path that doesn't get interpreted literally, instead, it acts as an expression that takes whichever actual string will be present at this position and stores it under the parameter named slug.

[0:41] You may be familiar with path parameters if you worked on backend applications in the past. This is no different. We access the actual value of this parameter in the argument to the responseResolver function. Let's spread that object argument and get the key named params from it.

[0:57] Params is an object that holds all found path parameters, where its keys represent parameter names, like the slug we have over here, and its values equal to those parameters' values.

[1:09] The slug parameter will be different for every movie our application tries to fetch. We can check the individual movie slugs and return different responses for different movies. We will reuse the same static data from the featuredMovies handler we wrote before to stay consistent.

[1:40] To keep our network description robust, we will return a not-found response for any other slug by constructing an HTTP response instance and setting its status to 404. Once we save the changes, we can see that our application displays the correct details depending on the movie we click on.