Exercise: Using @requires & @external
🎯 Goal: Query for a listing's "moneyValueGuaranteed" field, a Boolean
type. This field should live in the reviews subgraph. It also requires a listing's costPerNight and a review's overallRating.
Open up Explorer. When you run the operation below, you'll get an error!
query GetListingValue {listing(id: "listing-1") {titlemoneyValueGuaranteed}}
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 theListing
type calledmoneyValueGuaranteed
, which returns aBoolean
type.subgraph-reviews/reviews.graphqltype Listing @key(fields: "id") {# other Listing fieldsmoneyValueGuaranteed: Boolean}Tag the
moneyValueGuaranteed
field with the@requires
directive, passing it thecostPerNight
field.subgraph-reviews/reviews.graphqlmoneyValueGuaranteed: Boolean @requires(fields: "costPerNight")Add the
Listing.costPerNight
field and tag it as@external
.subgraph-reviews/src/resolvers.jscostPerNight: Float @externalAdd the imports for both directives at the top of the file.
subgraph-reviews/reviews.graphql@link(url: "https://specs.apollo.dev/federation/v2.7"import: ["@key", "@requires", "@external"])Add a resolver function for the new field in
subgraph-reviews/src/resolvers.js
.subgraph-reviews/src/resolvers.jsListing: {// other Listing resolversmoneyValueGuaranteed: (listing, _, { dataSources }) => {return dataSources.reviewsDb.calculateMoneyValueGuarantee(listing.costPerNight,listing.id);},}
BONUS: Examine the query plan
Here's the operation we're running:
query GetListingValue {listing(id: "listing-1") {titlemoneyValueGuaranteed}}
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.