Intercept and Mock GraphQL Mutations in MSW

Share this video with your friends

Social Share Links

Send Tweet
Published 7 months ago
Updated 7 months ago

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.

egghead
egghead
~ 3 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today