- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Diagnose Invalid Mutations in GraphQL
Bethany's Pie Shop lets home bakers catalog and share pies by category (fruit, cream, nut, savory). The catalog API already stores pie data in memory; your job is to expose it correctly over GraphQL: one reusable query for browsing by category, a validated mutation for submitting new pies, a live subscription so browsing clients see new pies the moment they are added, and a polling fallback for clients where an open connection is not worth the cost.
Lab Info
Table of Contents
-
Challenge
Step 1: Explore the Pie Catalog API
Bethany's Pie Shop runs a community catalog where home bakers list pies by category (fruit, cream, nut, savory) and browse what others have shared. The catalog data already lives in memory in
src/data.ts, and you won't edit it. In this lab you build the GraphQL layer on top of that data.You work in five files.
src/queries.tsandsrc/mutations.tsrun a query and a mutation throughgraphql({ schema, source, variableValues }).src/schema.tsholds the schema and its validation.src/subscriptions.tsopens subscriptions, andsrc/polling.tsprovides a polling alternative.src/pubsub.tsalready exports the sharedpubsubinstance and the topic namePIE_ADDED_TOPIC. TheAddPieInputtype insrc/schema.tscarries adescriptionon itscategoryandpricefields. Those descriptions are the schema's own documentation, and they state the rules the validation in Step 3 must enforce. When the catalog should reject an input, rereading the field's description is the first thing to do. ### Checking Your Progress as You WorkEach task is graded automatically when you complete it, and you can run the same checks yourself. The Terminal opens in the folder that holds
package.json. To check one task, put its name in quotes:bash runTest.sh "task 2.1"To run every check, and then the type check:
npx --no-install vitest run --reporter=dot npm run typecheckExpect failures at first. The starter is unfinished on purpose, so each task's check fails until you complete that task, and a first run of the whole suite shows many failures. Each failure message names the task it belongs to, and that check goes from failing to passing as you work. A passing single-task run shows
Tests 1 passed. After npm prints the script header, the type check prints nothing when it passes and lists each error with its file when it fails. -
Challenge
Step 2: Query pies by category with typed variables
src/queries.tsholds a constant,PIES_BY_CATEGORY_QUERY, that declares two variables in its document:$categoryand$sortBy. The category variable is required; the sort variable is optional. The operation is namedPiesByCategoryand selects the schema'spiesfield, so its results arrive underresult.data.pies. The query text is written once and never changes for the rest of this step. Every difference in behavior comes from what you put invariableValueswhen you callgraphql().graphql()resolves to a result object instead of throwing. That object carriesdatawhen execution produced a result anderrorswhen something failed, so you read the pies fromresult.dataand treat it as possibly missing. Typed variables also let the same query text run for any category without string interpolation. Now reuse that same query text for a second call site. Because$sortByis already declared inPIES_BY_CATEGORY_QUERY, adding it tovariableValuesis enough to change what comes back, and the resolver already knows how to sort by it. This is the payoff of keeping the document and its variables separate: one string, many behaviors. -
Challenge
Step 3: Add pies through a validated input mutation
With browsing in place, the next piece is letting bakers add their own pies.
src/mutations.tsdeclaresADD_PIE_MUTATION, a document that sends its argument through a singleinputvariable and selects backid,name,category, andprice. The mutation's result is exactly the fields you ask for, nothing more.graphql()reports a rejected mutation inresult.errorsinstead of throwing, sosubmitNewPiehas to throw the first error itself for a caller to see why a pie was rejected. Task 3.1 gives you a working submit path, and it also exposes a gap.addPie's resolver runsvalidatePieCategoryandvalidatePiePricefromsrc/schema.tsbefore it stores anything, but both are empty, so every input passes.To see it, run
npm run devin the Terminal and open the Web Browser tab. Enter any name, such asTest Pie,candyas the category and500as the price, then select Add pie. The page shows a green confirmation such asAdded Test Pie (candy, $500.00) to the catalog., even though the catalog should refuse both values. That message is the bug. PressCtrl+Cin the Terminal to stop the server.The Pie category field in the form suggests the allowed values as you type, the way an autocomplete does, and the
descriptionof each field onAddPieInputinsrc/schema.tsdocuments the rule behind it. Before you write any code, read both descriptions and name the rule each value breaks. Those two cues tell you whycandyand500should be rejected: the input is wrong, and the resolver validation that should report it is empty. You fix the validation in the next tasks, starting with the category field.This lab checks the rules in the resolver because that is where you can practice reading a rule and enforcing it. In a production schema, a fixed set of categories is better modeled as a GraphQL
enum, which makes the schema itself reject unknown values before any resolver runs, and money is better stored as integer cents than as aFloat. The price check works the same way as the category check: read the bound from the field's own description, then enforce it by throwing. A validation function that returns normally is read as "input accepted," so the only way to reject a bad price is to throw before the function returns. -
Challenge
Step 4: Publish live pie updates over a subscription
A mutation and a subscription share information about what happened only through the channel between them. That channel is a Pub/Sub (publish/subscribe) channel: one side publishes events on a named topic and any number of listeners receive them. In code it is the
PubSubclass fromgraphql-subscriptions.src/pubsub.tsalready exports a sharedpubsubinstance and a topic name,PIE_ADDED_TOPIC. What's missing are the two ends that use it: something that publishes on it, and something that reads from it.resolveAddPiealready callsnotifyPieAddedafter it stores a pie, so you only complete the function body. With publishing wired up, thepieAddedsubscription field needs a source to read from.PubSub.asyncIterator(topic)produces exactly that: an async iterator that yields each payload published on the given topic, in order, for as long as the subscription stays open. This lab pinsgraphql-subscriptions2.0.0, whereasyncIteratoris the correct method. Version 3 renames itasyncIterableIteratorand deprecates the old name, so you may see that name in newer examples. The field'sresolvefunction already unwrapspayload.pieAddedfor each event. Right now every subscriber topieAddedsees every pie, regardless of the category they asked for.graphql-subscriptionsshipswithFilterfor exactly this: it wraps an async iterator with a filter function that runs on every payload, and only forwards the ones where the filter returnstrue. ThepieAddedsubscription field is already wrapped inwithFilter, and the iterator it wraps is thesubscribePieAddedyou already completed, so you only complete the filter function. -
Challenge
Step 5: Compare concurrent subscriptions with polling
A subscription is only useful if every listener actually gets the event.
src/subscriptions.tsdeclaresPIE_ADDED_SUBSCRIPTION, the same kind of document you've been building, and graphql-js's ownsubscribe()function returns an async iterator for it. Callsubscribe()more than once against the same schema and you get independent iterators that all see the same published events.graphql-subscriptionsregisters its listener on the firstnext()call, so an iterator that has not callednext()yet misses an event published before it. Callnext()on every iterator before you publish. Not every client should hold a subscription open.src/polling.tsbuilds the other half of the delivery story: a plain function,pollForNewPies, that a client can call on a schedule instead of keeping a connection alive, using the timestamp of its last check to ask for only what's new. It builds onlistPiesAddedSince(since)insrc/data.ts, whichsrc/polling.tsalready imports. That helper returns a new array of the pies whose numericcreatedAtis strictly greater thansince, in store order. The last piece is deciding which delivery method a given client should use. An open subscription that never receives an event is still a held connection, and past some number of idle connections, polling on a schedule costs less than keeping all of them open.IDLE_CONNECTION_THRESHOLDinsrc/polling.tsmarks that line. -
Challenge
Step 6: Run the application
Every task is done, and each one was graded the moment you completed it. What you have not done yet is watch the whole application run at once, which is where the pieces you wrote separately become a single working program.
Start the Application
In the Terminal, start the dev server:
npm run devSwitch to the Web Browser tab. The page shows the Bethany's Pie Shop catalog: a category menu, the pies in that category, and a form to submit a new pie. Choose nut and the list shows Pecan Pie.
Now repeat the bad input from Step 3. Enter
candyas the category and500as the price, then select Add pie. The page now shows the error message from your validation instead of adding the pie. Then fix the input, using the category suggestions and the field descriptions: submit a valid pie, such asLemon Pieinfruitfor11, and choose fruit to see it in the list.Press
Ctrl+Cin the Terminal to stop the server before you run the final checks. ### Run the Final ChecksIn the Terminal, run every check and the type check on your finished code:
npx --no-install vitest run --reporter=dot npm run typecheckThe suite ends with
Tests 12 passed, and the type check prints only the npm script header. Congratulations on completing the lab. You built the GraphQL layer behind a pie catalog for Bethany's Pie Shop: queries that reuse one document with typed variables, anaddPiemutation whose validators reject input the schema documents as invalid, apieAddedsubscription fed through Pub/Sub, and a polling path with a rule for choosing between them.Along the way you read a schema's own descriptions to find out why an input should be rejected, then enforced those rules in code. You can use the same habit on any GraphQL API, and the same trade-off between a held connection and a scheduled check on any live-update feature you design.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.