16. Exercise: Implement the likeTrack mutation
1m

Instructions

Goal: Increase the numberOfLikes for a specific track.

  • Bonus Challenge: Optimize these mutation response types by creating a MutationResponse interface.

  • Resource: Apollo Docs: Structuring mutation responses

  1. Update schema.

    type Mutation {
    "Increment the number of views of a given track, when the track card is clicked"
    incrementTrackViews(trackId: ID!): TrackMutationResponse!
    "Like a specific track"
    likeTrack(trackId: ID!): TrackMutationResponse!
    }
  2. Have a look at the cats-api.js data source. Which of these methods will help us make the data changes we need? (We'll use this method in the next step.)

    incrementTrackLikes(trackId) {
    return this.patch(`track/${trackId}/numberOfLikes`);
    }
  3. Add resolver.

    likeTrack: async (parent, { trackId }, { dataSources }) => {
    const track = await dataSources.catsAPI.incrementTrackLikes(trackId);
    return {
    code: 200,
    success: true,
    message: `Successfully incremented number of likes for track ${trackId}`,
    track,
    };
    },

Check your work

You should be able to run this mutation in Sandbox:

mutation LikeTrack($trackId: ID!) {
likeTrack(trackId: $trackId) {
code
success
message
track {
id
numberOfLikes
}
}
}

In the Variables panel:

{"trackId": "c_0"}

Your response should look something like this (note that the numberOfLikes value may be different):

{
"data": {
"likeTrack": {
"code": 200,
"success": true,
"message": "Successfully incremented number of likes for track c_2",
"track": {
"id": "c_0",
"numberOfLikes": 4
}
}
}
}
Previous
Next