Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

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 platform
Lab Info
Level
Beginner
Last updated
Nov 23, 2026
Duration
1h 0m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. 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.ts and src/mutations.ts run a query and a mutation through graphql({ schema, source, variableValues }). src/schema.ts holds the schema and its validation. src/subscriptions.ts opens subscriptions, and src/polling.ts provides a polling alternative. src/pubsub.ts already exports the shared pubsub instance and the topic name PIE_ADDED_TOPIC. The AddPieInput type in src/schema.ts carries a description on its category and price fields. 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 Work

    Each 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 typecheck
    

    Expect 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.

  2. Challenge

    Step 2: Query pies by category with typed variables

    src/queries.ts holds a constant, PIES_BY_CATEGORY_QUERY, that declares two variables in its document: $category and $sortBy. The category variable is required; the sort variable is optional. The operation is named PiesByCategory and selects the schema's pies field, so its results arrive under result.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 in variableValues when you call graphql().

    graphql() resolves to a result object instead of throwing. That object carries data when execution produced a result and errors when something failed, so you read the pies from result.data and 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 $sortBy is already declared in PIES_BY_CATEGORY_QUERY, adding it to variableValues is 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.

  3. 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.ts declares ADD_PIE_MUTATION, a document that sends its argument through a single input variable and selects back id, name, category, and price. The mutation's result is exactly the fields you ask for, nothing more.

    graphql() reports a rejected mutation in result.errors instead of throwing, so submitNewPie has 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 runs validatePieCategory and validatePiePrice from src/schema.ts before it stores anything, but both are empty, so every input passes.

    To see it, run npm run dev in the Terminal and open the Web Browser tab. Enter any name, such as Test Pie, candy as the category and 500 as the price, then select Add pie. The page shows a green confirmation such as Added Test Pie (candy, $500.00) to the catalog., even though the catalog should refuse both values. That message is the bug. Press Ctrl+C in 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 description of each field on AddPieInput in src/schema.ts documents the rule behind it. Before you write any code, read both descriptions and name the rule each value breaks. Those two cues tell you why candy and 500 should 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 a Float. 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.

  4. 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 PubSub class from graphql-subscriptions. src/pubsub.ts already exports a shared pubsub instance 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. resolveAddPie already calls notifyPieAdded after it stores a pie, so you only complete the function body. With publishing wired up, the pieAdded subscription 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 pins graphql-subscriptions 2.0.0, where asyncIterator is the correct method. Version 3 renames it asyncIterableIterator and deprecates the old name, so you may see that name in newer examples. The field's resolve function already unwraps payload.pieAdded for each event. Right now every subscriber to pieAdded sees every pie, regardless of the category they asked for. graphql-subscriptions ships withFilter for exactly this: it wraps an async iterator with a filter function that runs on every payload, and only forwards the ones where the filter returns true. The pieAdded subscription field is already wrapped in withFilter, and the iterator it wraps is the subscribePieAdded you already completed, so you only complete the filter function.

  5. Challenge

    Step 5: Compare concurrent subscriptions with polling

    A subscription is only useful if every listener actually gets the event. src/subscriptions.ts declares PIE_ADDED_SUBSCRIPTION, the same kind of document you've been building, and graphql-js's own subscribe() function returns an async iterator for it. Call subscribe() more than once against the same schema and you get independent iterators that all see the same published events.

    graphql-subscriptions registers its listener on the first next() call, so an iterator that has not called next() yet misses an event published before it. Call next() on every iterator before you publish. Not every client should hold a subscription open. src/polling.ts builds 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 on listPiesAddedSince(since) in src/data.ts, which src/polling.ts already imports. That helper returns a new array of the pies whose numeric createdAt is strictly greater than since, 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_THRESHOLD in src/polling.ts marks that line.

  6. 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 dev
    

    Switch 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 candy as the category and 500 as 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 as Lemon Pie in fruit for 11, and choose fruit to see it in the list.

    Press Ctrl+C in the Terminal to stop the server before you run the final checks. ### Run the Final Checks

    In the Terminal, run every check and the type check on your finished code:

    npx --no-install vitest run --reporter=dot
    npm run typecheck
    

    The 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, an addPie mutation whose validators reject input the schema documents as invalid, a pieAdded subscription 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

Pluralsight’s AI authoring technology is designed to accelerate the creation of hands-on, technical learning experiences. Serving as a first-pass content generator, it produces structured lab drafts aligned to learning objectives defined by Pluralsight’s Curriculum team. Each lab is then enhanced by our Content team, who configure the environments, refine instructions, and conduct rigorous technical and quality reviews. The result is a collaboration between artificial intelligence and human expertise, where AI supports scale and efficiency, and Pluralsight experts ensure accuracy, relevance, and instructional quality, helping learners build practical skills with confidence.

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.

Get started with Pluralsight