7. Exercise: Defining & contributing to an entity
1m

Exercise: Defining & contributing to an entity

🎯 Goal: for a listing's title, overallRating and reviews information.

Open up Explorer. When you run the below, you'll get an error!

query GetListingDetails {
listing(id: "listing-1") {
title
overallRating
reviews {
rating
text
}
}
}

After successfully completing the exercise, you should get data back when running the GetListingDetails again.

Hints

First, define the (remember, you need two things to do this!).

Then, contribute the two (overallRating and reviews) for the in the schema. Write separate functions for each .

✅ Solution

Expand the sections below for a quick copy-paste, or follow the instructions to go step-by-step.

  1. In subgraph-reviews/reviews.graphql, tag the Listing type as an using @key with the id as the key .

    subgraph-reviews/reviews.graphql
    type Listing @key(fields: "id") {
    id: ID!
    }
  2. Add a Listing reference in subgraph-reviews/src/resolvers.js.

    subgraph-reviews/src/resolvers.js
    Listing: {
    __resolveReference(listing) {
    // listing looks something like this { id: "listing-1"}
    // console.log(listing);
    return listing;
    },
    }
  3. Add two : overallRating that returns a Float and reviews that returns an list of Review types.

    subgraph-reviews/reviews.graphql
    type Listing @key(fields: "id") {
    id: ID!
    overallRating: Float
    reviews: [Review!]!
    }
  4. Add a function for Listing.overallRating.

    subgraph-reviews/src/resolvers.js
    Listing: {
    __resolveReference(listing) {
    return listing;
    },
    overallRating: ({ id }, _, { dataSources }) => {
    return dataSources.reviewsDb.getOverallRatingForListing(id);
    },
    },
  5. Add a for Listing.reviews.

    subgraph-reviews/src/resolvers.js
    Listing: {
    __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 we're running:

query GetListingDetails {
listing(id: "listing-1") {
title
overallRating
reviews {
rating
text
}
}
}

Examine the for the .

In the query plan, which two fields is the router asking for that are not included in the original GraphQL operation?
Why are those two fields included in the query plan?
Previous

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.