Challenge 1: Add a Second Loader to Context — Possible Solution ==================================================================== import express from "express"; import { expressMiddleware } from "@apollo/server/express4"; const app = express(); const server = new ApolloServer({ typeDefs, resolvers }); await server.start(); app.use( "/graphql", express.json(), expressMiddleware(server, { async context({ req }) { return { userLoader: createUserLoader(pool), postsByAuthorLoader: createPostsByAuthorLoader(pool), // NEW }; }, }) ); app.listen(4000); // A matching batch function, following the same pattern as Challenge 1 // from Chapter 5 (batching a one-to-many relationship): function createPostsByAuthorLoader(pool) { return new DataLoader(async (authorIds) => { const [rows] = await pool.query( "SELECT * FROM posts WHERE author_id IN (?)", [authorIds] ); return authorIds.map((authorId) => rows.filter((post) => post.author_id === authorId) ); }); } WHY THIS WORKS -------------- - Both loaders are created INSIDE the same context callback, on every single request — postsByAuthorLoader isn't hoisted out any more than userLoader is, which is exactly the discipline the chapter's tip box insists on. Adding a second loader doesn't change WHERE loaders get created, only that there are now two of them built the same way. - The context object simply grows to carry both loaders as separate named properties — any resolver needing user data reads context.userLoader, and any resolver needing a user's posts reads context.postsByAuthorLoader, each getting its own independent, per-request cache and batching behavior. - createPostsByAuthorLoader follows the one-to-many batching shape (using .filter() to group multiple posts per author) rather than the one-to-one shape (using .find() for a single user per id) — the same distinction covered in Chapter 5's own comments-batching challenge, applied here to a different relationship (posts grouped by author instead of comments grouped by post). - This scales naturally: a real production schema typically needs several DataLoaders (one per relationship that risks an N+1 pattern), and the context function is simply the one place all of them get constructed together, once per request.