Intercept and Mock GraphQL Mutations in MSW

Share this video with your friends

Social Share Links

Send Tweet

In this lesson, you will use the Mock Service Worker graphql.mutation() request handler to allow the users to leave reviews for the movie they've watched.

Lecturer: [0:00] To let our users leave reviews for their favorite movies, we have a createReview form on the client and the remix action on the server to handle its submissions.

[0:09] The review itself is created by performing a GraphQL mutation called addReview. It has two variables, the author who submits the review and the review itself, and it sends back a review object with the ID and text to the client to display the review in the UI.

[0:25] We will follow the shape of this mutation and create a request handler for it. In our handlers, we will call graphQL.mutation method to intercept a GraphQL mutation. Same as with queries, the first argument to the GraphQL mutation method will be the operation name, addReview.

[0:42] In the response resolver, access the mutation variables and get the author and the review input data sent from the client. Using the movieId property on the review input, let's find that movie from the collection of all movies by its ID.

[1:04] Next, let's construct the new review object by taking the review sent by the user and adding the missing fields to complete it. Keep in mind that the data structures you describe will depend on your particular use case. We will check the existing movie reviews and add a new review to that list.

[1:28] Finally, respond with a JSON response whose data follows the structure of our mutation. With this request handler in place, we can go to any movie we want and submit a new review for it just as our users would.