从零重写:空目录到 10 个测试全过Rewrite it: from an empty directory to all 10 tests passing
不给答案。给 schema、给数据源、给测试、给四级提示。这一关是分界线。No answer key. You get the schema, the data source, the tests, and four levels of hints. This stage is the dividing line.
这一页有什么On this page4
- 在没有参考代码的情况下从空目录搭出一个 federation subgraphBuild a federation subgraph from an empty directory, with no reference code
- 独立实现四个 resolver 并自己发现三处埋雷Write the four resolvers on your own and find the three hidden problems yourself
- 独立实现六个 Spring 端点并选对状态码Write the six Spring endpoints on your own and pick the right status code for each
- 用测试 + verify 脚本 + curl 三种方式验证自己的实现Check your own work in three ways: the tests, the verify script, and curl
填空和跟写只证明你看懂了。真正的考试是打开一个空编辑器。这一关比真实考试更难 —— 连脚手架都要你自己搭。Filling in blanks and typing along only prove that you followed the text. The real exam starts with an empty editor. This stage is harder than the real exam, because even the project setup is yours to write.
graphql-federation-practice/参考项目 —— 做完之后再对照,不要提前看The reference project — compare against it after you finish; do not look early
graphql-federation-practice/为什么必须做这一关Why this stage is required
前面每一节的 L3 练习里,你已经分别写过四个 resolver 和六个端点。这一关是把它们放回一个完整项目里—— 加上你自己搭的 schema 加载、context 构造、依赖配置。
而且这一关会强迫你面对一件事: 没有人告诉你埋雷在哪。你要自己写 loader、自己写 mutation —— 如果你在这里犯了和 starter 一样的错 (方法名、签名、catch 吞错误), 那说明前面那几节只是「看懂了」。
不要跳过这一关直接看答案。撞墙的地方才是你真正的薄弱点。
In the L3 exercises of the earlier lessons you have already written all four resolvers and all six endpoints, separately. This stage puts them back inside one complete project — along with schema loading, context construction and dependency setup that you build yourself.
And this stage forces you to face one thing: nobody tells you where the traps are. You write the loader yourself, you write the mutation yourself. If you make the same mistakes the starter made (method name, signature, catch swallowing the error), then those earlier lessons only got you as far as “I followed along”.
Do not skip this and go straight to the answer. The wall you hit is where your real weak spot is.
建议的做法A suggested order of work
- 新建目录,不要在源项目里改。比如
~/Downloads/my-order-subgraph。 源项目留着最后对照。 - 先让空服务器能起来。
npm init→ 装依赖 → 写一个最小 schema (只有type Query { ping: String })→npm start能看到Subgraph ready at ...再往下走。这是所有项目的正确起手式。 - 把 schema、数据源、测试抄进去。这三样是「题目」,不是「答案」。 抄它们等于把考场搭起来。
- 一个测试一个测试地攻。先让
User.orders的两条过, 再shippingInfo,依次推进。 - 10 个测试全绿之后,写 verify 脚本。测试只覆盖单元层面;
_service和_entities要自己验。 - Java 那半独立做。它和 subgraph 没有代码关联,可以完全分开。
- 卡住超过 20 分钟再看提示。提示是四级递进的。
- New directory. Do not edit inside the source project. Something like
~/Downloads/my-order-subgraph. Keep the source project for comparing at the end. - Get an empty server running first.
npm init→ install dependencies → write a minimal schema (justtype Query { ping: String }) → runnpm startand seeSubgraph ready at ...before you go any further. That is the right opening move on any project. - Copy in the schema, the data sources and the tests. Those three are the question, not the answer. Copying them is how you set up the exam room.
- Attack one test at a time. Get the two
User.orderstests green, thenshippingInfo, and keep going in order. - Once all 10 tests are green, write the verify script. The tests only cover the unit level;
_serviceand_entitiesyou have to check yourself. - Do the Java half on its own. It shares no code with the subgraph, so you can keep them fully separate.
- Stuck for more than 20 minutes? Then look at a hint. The hints come in four escalating levels.
动手做Get your hands on it
填空只是过渡。真正掌握的标准,是在没有答案的时候从头写出来 —— 所以做完 L2 之后一定要往 L3、L4 走。Filling blanks is a stepping stone. The real bar is writing it from nothing, so once L2 is comfortable, push on to L3 and L4.
空目录开始,搭出一个 Apollo Federation subgraph, 实现四个 resolver 加一个 mutation,让 10 个测试全过, 并且 _service 和 _entities 都能正常工作。不要打开源项目的 orderResolvers.js。
Starting from an empty directory, build an Apollo Federation subgraph. Write four resolvers plus one mutation, get all 10 tests passing, and make both _service and _entities work. Do not open orderResolvers.js from the source project.
- 用 @apollo/server + @apollo/subgraph 起一个 subgraph,监听 4000Start a subgraph with @apollo/server + @apollo/subgraph, listening on 4000
- schema 从 .graphql 文件读入,用 buildSubgraphSchema 组装Read the schema from a .graphql file and assemble it with buildSubgraphSchema
- 每个请求构造 context:三个数据源、两个 DataLoader、一个 correlationIdBuild the context per request: three data sources, two DataLoaders, one correlationId
- correlationId 优先取请求头 x-correlation-id,没有就生成Take correlationId from the x-correlation-id request header, and generate one when it is absent
- 实现 User.__resolveReference:把 representation 变成本地对象Write User.__resolveReference: turn the representation into a local object
- 实现 User.orders:按 user.id 取订单,[Order!]! 所以绝不返回 nullWrite User.orders: read orders by user.id; the type is [Order!]!, so never return null
- 实现 Order.shippingInfo:必须走 DataLoader 防 N+1;可空,找不到返回 nullWrite Order.shippingInfo: it must go through the DataLoader to prevent N+1; it is nullable, so return null when nothing is found
- 实现 Query.order:走 DataLoader;找不到抛带 ORDER_NOT_FOUND 的 GraphQLErrorWrite Query.order: go through the DataLoader; when nothing is found, throw a GraphQLError carrying ORDER_NOT_FOUND
- 实现 Query.orders:校验 userId;[Order!]! 所以兜底 []Write Query.orders: validate userId; the type is [Order!]!, so fall back to []
- 实现 Mutation.createOrder:先查商品价格补全 items,再创建;校验失败抛 INVALID_INPUTWrite Mutation.createOrder: look up product prices to complete items first, then create; throw INVALID_INPUT when validation fails
- 两个 DataLoader 的 batch 函数:返回数组的长度与顺序必须和 keys 一一对应The batch function of both DataLoaders: the array it returns must match keys in both length and order
- 所有 resolver 都用 try/catch,catch 第一行放行已有的 GraphQLErrorWrap every resolver in try/catch, and let an existing GraphQLError pass through on the first line of catch
- 所有日志和错误 extensions 里带上 correlationIdCarry correlationId in every log line and in the extensions of every error
这一关的意义就在于「没有答案也能写出来」。请确认你已经在本机建好文件、跑过验证命令,再打开参考答案对照。The whole point of this level is writing it with no answer in front of you. Create the files on your machine and run the verification commands first, then come back and compare.
给你 OrderService 的方法签名和五个测试。 自己搭一个 Spring Boot 项目,写出六个端点。不要打开源项目的 OrderController.java。
You are given the method signatures of OrderService and five tests. Set up a Spring Boot project yourself and write six endpoints. Do not open OrderController.java from the source project.
- Spring Boot 3.3 + Java 17,依赖 web / validation / actuator / testSpring Boot 3.3 + Java 17, with the web / validation / actuator / test dependencies
- 一个 @RestController,构造器注入 OrderServiceOne @RestController, with OrderService injected through the constructor
- GET /api/orders:?userId= 传了就按用户过滤,没传返回全部;200GET /api/orders: filter by user when ?userId= is given, return everything when it is not; 200
- GET /api/orders/{id}:200;找不到时由全局异常处理器给出 404(控制器不要 catch)GET /api/orders/{id}: 200; when nothing is found, the global exception handler answers 404 (do not catch it in the controller)
- GET /api/orders/user/{userId}:200GET /api/orders/user/{userId}: 200
- POST /api/orders:@Valid 校验请求体;成功返回 201 CreatedPOST /api/orders: validate the request body with @Valid; on success return 201 Created
- PATCH /api/orders/{id}/status:body 是 {"status":"..."};转成 OrderStatus;缺失或非法值返回 400;成功 200PATCH /api/orders/{id}/status: the body is {"status":"..."}; convert it to OrderStatus; a missing or invalid value returns 400; on success 200
- DELETE /api/orders/{id}:204 No ContentDELETE /api/orders/{id}: 204 No Content
- 六个端点都用 SLF4J 打日志,并带上 MDC 里的 correlationIdAll six endpoints log through SLF4J and carry the correlationId from MDC
- 自己写一个 CorrelationIdFilter:读 X-Correlation-ID 头,没有就生成 UUID,放进 MDC,finally 里清理Write your own CorrelationIdFilter: read the X-Correlation-ID header, generate a UUID when it is absent, put it in MDC, and clear it in finally
- 自己写 GlobalExceptionHandler:EntityNotFoundException → 404,MethodArgumentNotValidException → 400Write your own GlobalExceptionHandler: EntityNotFoundException → 404, MethodArgumentNotValidException → 400
这一关的意义就在于「没有答案也能写出来」。请确认你已经在本机建好文件、跑过验证命令,再打开参考答案对照。The whole point of this level is writing it with no answer in front of you. Create the files on your machine and run the verification commands first, then come back and compare.
换一道题也能用Works on other problems too
考试不会原题重考。真正能带走的是「看到这种信号 → 伸手去拿这个解法」。The exam will not reuse the same question. What you take away is the reflex: see this signal, reach for that solution.
- 起手式:先让空服务器能起来(能看到 ready 日志),再写业务逻辑。First step: get an empty server to start, so you can see the ready log. Only then write the logic.
- schema、数据源、测试是「题目」,抄进来等于搭好考场;resolver 和 index.js 是「答案」,自己写。The schema, the data source and the tests are the question, so copying them in just sets up the exam. The resolvers and index.js are the answer, so write those yourself.
- 写跨模块调用之前先抄方法名与签名表 —— 这能挡掉 starter 里那两处埋雷同类的错误。Before you write a call across modules, write down the method names and signatures. That stops the same kind of error as the two hidden problems in the starter code.
- 10 个测试全绿只是及格线,还要用 verify 脚本验 _service 和 _entities。All 10 tests passing is only the minimum. You still need the verify script to check _service and _entities.
- Java 那半和 subgraph 无代码关联,可以完全独立做。The Java half shares no code with the subgraph, so you can do it completely on its own.