Exercise: Defining & contributing to an entity
🎯 Goal: Query for a listing's title, overallRating and reviews information.
Open up Explorer. When you run the operation below, you'll get an error!
query GetListingDetails {listing(id: "listing-1") {titleoverallRatingreviews {ratingtext}}}
After successfully completing the exercise, you should get data back when running the GetListingDetails operation again.
Hints
First, define the entity (remember, you need two things to do this!).
Then, contribute the two fields (overallRating and reviews) for the entity in the schema. Write separate resolver functions for each field.
✅ Solution
Expand the sections below for a quick copy-paste, or follow the instructions to go step-by-step.
In
subgraph-reviews/reviews.graphql, tag theListingtype as an entity using@keywith theidas the key field.subgraph-reviews/reviews.graphqltype Listing @key(fields: "id") {id: ID!}Add a
Listingreference resolver insubgraph-reviews/src/resolvers.js.subgraph-reviews/src/resolvers.jsListing: {__resolveReference(listing) {// listing looks something like this { id: "listing-1"}// console.log(listing);return listing;},}Add two fields:
overallRatingthat returns aFloatandreviewsthat returns an list ofReviewtypes.subgraph-reviews/reviews.graphqltype Listing @key(fields: "id") {id: ID!overallRating: Floatreviews: [Review!]!}Add a resolver function for
Listing.overallRating.subgraph-reviews/src/resolvers.jsListing: {__resolveReference(listing) {return listing;},overallRating: ({ id }, _, { dataSources }) => {return dataSources.reviewsDb.getOverallRatingForListing(id);},},Add a resolver for
Listing.reviews.subgraph-reviews/src/resolvers.jsListing: {__resolveReference(listing) {return listing;},overallRating: ({ id }, _, { dataSources }) => {return dataSources.reviewsDb.getOverallRatingForListing(id);},reviews: ({ id }, _, { dataSources }) => {return dataSources.reviewsDb.getReviewsByListing(id);},},
BONUS: Examine the query plan
Here's the operation we're running:
query GetListingDetails {listing(id: "listing-1") {titleoverallRatingreviews {ratingtext}}}
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.