Exercise: Referencing an entity
🎯 Goal: Get the most recent reviews. For each review, show the listing's title, number of beds and cost per night.
Open up Explorer. When you run the operation below, you'll get an error!
query GetRecentReviews {recentReviews {textratinglisting {titlenumOfBedscostPerNight}}}
After successfully completing the exercise, you should get data back when running the GetRecentReviews operation again.
Hints
✅ Solution
Expand the sections below for a quick copy-paste, or follow the instructions to go step-by-step.
In
subgraph-reviews/reviews.graphql, add a new field to theReviewtype calledlisting, which returns aListingtype.subgraph-reviews/reviews.graphqltype Review {id: ID!"Comment the author has written"text: String!"The numerical rating for the review target, on a scale of 1-5, with 5 being excellent."rating: Float!"The listing associated with the review"listing: Listing}Find the
Review.listingresolver insubgraph-reviews/src/resolvers.js.subgraph-reviews/src/resolvers.jsReview: {listing: () => {// TODO},},Inside the resolver, return an entity representation of a
Listingentity.subgraph-reviews/src/resolvers.jsReview: {listing: (review) => {return { id: review.listingId };},},Remember that the first parameter of a resolver function is the
parent, which in this case is theReviewtype returned by theQuery.recentReviewsresolver. Feel free to add aconsole.logbefore returning the entity representation to find out what is available in thereviewobject.To return an entity representation, we need to return an object with the
idproperty set to thelistingIdvalue. We could also add a__typename, but Apollo Server takes care of that for us automatically.
BONUS: Examine the query plan
Here's the operation we're running:
query GetRecentReviews {recentReviews {textratinglisting {titlenumOfBedscostPerNight}}}
Examine the query plan for the operation.
Share your questions and comments about this lesson
Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.
You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.