10. Exercise: Using @requires & @external
1m

Exercise: Using @requires & @external

🎯 Goal: for a listing's "moneyValueGuaranteed" , a Boolean type. This should live in the reviews . It also requires a listing's costPerNight and a review's overallRating.

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

query GetListingValue {
listing(id: "listing-1") {
title
moneyValueGuaranteed
}
}

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

Hints

✅ 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, add a new to the Listing type called moneyValueGuaranteed, which returns a Boolean type.

    subgraph-reviews/reviews.graphql
    type Listing @key(fields: "id") {
    # other Listing fields
    moneyValueGuaranteed: Boolean
    }
  2. Tag the moneyValueGuaranteed with the @requires , passing it the costPerNight .

    subgraph-reviews/reviews.graphql
    moneyValueGuaranteed: Boolean @requires(fields: "costPerNight")
  3. Add the Listing.costPerNight and tag it as @external.

    subgraph-reviews/src/resolvers.js
    costPerNight: Float @external
  4. Add the imports for both at the top of the file.

    subgraph-reviews/reviews.graphql
    @link(
    url: "https://specs.apollo.dev/federation/v2.7"
    import: ["@key", "@requires", "@external"]
    )
  5. Add a function for the new in subgraph-reviews/src/resolvers.js.

    subgraph-reviews/src/resolvers.js
    Listing: {
    // other Listing resolvers
    moneyValueGuaranteed: (listing, _, { dataSources }) => {
    return dataSources.reviewsDb.calculateMoneyValueGuarantee(
    listing.costPerNight,
    listing.id
    );
    },
    }

BONUS: Examine the query plan

Here's the we're running:

query GetListingValue {
listing(id: "listing-1") {
title
moneyValueGuaranteed
}
}

Examine the for the .

In the query plan, what does the router ask for from the listings subgraph that's not included in the original GraphQL operation?
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.