When working with existing APIs, especially those you don't own, being able to take the original response and manipulate it can be a life-changer when iterating on features or reproducing bugs. In this lesson, you will learn to perform the original request and then use Mock Service Worker to patch it with whichever data you want.
Instructor: [0:00] With MSW, we can combine original and mock data in the same response using response patching. Let's create a new request handler for the featured movies endpoint that already responds with a list of actual production movies, and grab its request reference.
[0:21] Naturally, what we want to do is just fetch this intercepted request to get the original response. If we do this, this fetch call will create a new network entry for which MSW will find this matching request handler again, triggering another fetch call and resulting in an infinite loop.
[0:37] To prevent this from happening, MSW comes with a built-in API to bypass requests called bypass. Go to our fetch call and wrap the intercepted request instance in the bypass function call. This marks this request and instructs MSW to ignore any otherwise matching request handlers when it happens, which is precisely what we want to get the original response.
[0:59] The rest is regular fetch API response handling. We will await the response promise and then read its JSON body as the list of originalMovies. At this point, we can do whatever we want with the original response because it's just a plain JavaScript array.
[1:17] Let's return a new JSON response that will send back the originalMovies array, concatenated with the list of mock movies we have. With this request handler, our application receives a mix of the original data from the production API and the mock data from the request handler at the same time.