DrillLab
练习Practice

动手做Get your hands on it

练习跟着课文走 —— 每节课尾都有本课的练习。这一页是全部练习的总库,想集中刷题的时候来。 每个练习都写清了它来自哪一节,卡住了就回去看那一节。Practice follows the lessons — every lesson ends with the exercises for that lesson. This page is the whole library, for when you want to drill in one sitting. Each exercise names the lesson it came from, so you can go back when you stall.

0 / 148个做对过you got right

已筛到你正在学的《Federation 考试》。想看全部就点上面的「全部」。Filtered to Federation exam — the course you are on. Use “All” above to see everything.

练习Exercises

筛出 11 个练习(共 148 个)。Showing 11 of 148.
来自From GraphQL 是什么:一份 schema 加一堆 resolverWhat GraphQL is: one schema plus a set of resolvers · Federation 考试Federation exam
L2填空Fill the blanks补全 schema 的关键声明Fill in the key declarations of the schema

照真实 schema.graphql 补全。 三个空分别关系到「入口类型」「枚举」「输入类型」。

Fill this in from the real schema.graphql. The three blanks are the entry type, the enum and the input type.

GRAPHQLsrc/schema.graphql3 个空3 blanks
1 OrderStatus {
2 PENDING
3 PROCESSING
4 SHIPPED
5 DELIVERED
6 CANCELLED
7}
8
9type {
10 order(id: ID!): Order
11 orders(userId: ID!): [Order!]!
12}
13
14 OrderItemInput {
15 productId: ID!
16 quantity: Int!
17}
把 3 个空都填上才能检查(还差 3 个)Fill all 3 blanks to check (3 to go)
来自From 非空、列表,和那个没有 price 的 inputNon-null, lists, and the input that has no price · Federation 考试Federation exam
L2填空Fill the blanks给四个 TODO 各自选对兜底策略Pick the right fallback for each of the four TODOs

照 schema 的非空标记,给每个 resolver 填上正确的返回表达式。 想清楚「这个字段能不能是 null」。

Go by the non-null markers in the schema and write the right return expression for each resolver. Decide first whether the field is allowed to be null.

JSsrc/resolvers/orderResolvers.js3 个空3 blanks
1// schema: orders: [Order!]!
2async orders(user, _, { dataSources }) {
3 const orders = await dataSources.orderDataSource.getOrdersByUserId(user.id);
4 return orders [];
5}
6
7// schema: shippingInfo: ShippingInfo (可空)
8async shippingInfo(parent, _, { loaders }) {
9 const info = await loaders.shippingInfoLoader.load(parent.id);
10 return info ?? ;
11}
12
13// schema: order(id: ID!): Order (可空,但题目要求找不到时抛结构化错误)
14async order(_, { id }, { loaders, correlationId }) {
15 const order = await loaders.orderLoader.load(id);
16 if () {
17 throw new GraphQLError(`Order not found: ${id}`, {
18 extensions: { code: ErrorCodes.ORDER_NOT_FOUND, correlationId }
19 });
20 }
21 return order;
22}
把 3 个空都填上才能检查(还差 3 个)Fill all 3 blanks to check (3 to go)
来自From entity、@key 与 __resolveReferenceentity, @key and __resolveReference · Federation 考试Federation exam
L2填空Fill the blanks补全 entity 声明与引用解析Fill in the entity declaration and the reference resolver

三个空。第一个是 directive,第二个是标记「这不是我的字段」, 第三个是引用解析要返回什么。

Three blanks. The first is a directive, the second marks a field as not belonging to this service, and the third is what the reference resolver returns.

GRAPHQLschema.graphql + orderResolvers.js3 个空3 blanks
1# schema.graphql
2type User (fields: "id") {
3 id: ID!
4 orders: [Order!]!
5}
6
7# orderResolvers.js
8# User: {
9# __resolveReference(user, { dataSources, loaders }) {
10# return { id: };
11# },
12# ...
13# }
把 3 个空都填上才能检查(还差 3 个)Fill all 3 blanks to check (3 to go)
来自From N+1 问题与 DataLoaderThe N+1 problem and DataLoader · Federation 考试Federation exam
L2填空Fill the blanks修好 createOrderLoader 并写出 shippingInfoFix createOrderLoader and write shippingInfo

两个空。第一个要你填对数据源上真实存在的方法名, 第二个要你用 loader 而不是数据源。

Two blanks. The first wants the name of a method that really exists on the data source; the second wants you to go through the loader rather than the data source.

JSsrc/resolvers/orderResolvers.js2 个空2 blanks
1function createOrderLoader(orderDataSource) {
2 return new DataLoader(async orderIds => {
3 const orders = await Promise.all(
4 orderIds.map(id => orderDataSource.(id))
5 );
6 return orders;
7 });
8}
9
10// Order.shippingInfo —— 必须走 loader,否则 N+1 考点没答到
11async shippingInfo(parent, _, { dataSources, loaders, correlationId }) {
12 const shippingInfo = await loaders..load(parent.id);
13 return shippingInfo ?? null;
14}
把 2 个空都填上才能检查(还差 2 个)Fill all 2 blanks to check (2 to go)
来自From N+1 问题与 DataLoaderThe N+1 problem and DataLoader · Federation 考试Federation exam
L2Debug LabDebug LabDebug Lab · DataLoader 报 is not a functionDebug Lab · DataLoader reports is not a function

npm test,其中一个 DataLoader 相关的测试挂了。 报错指向 loader 内部。

You run npm test and one of the DataLoader tests fails. The error points inside the loader.

第 1 步 · 先看现象和代码,别急着改Step 1 · read the symptom and the code before you touch anything
● Order Resolvers › DataLoader functionality › should batch multiple order requests TypeError: orderDataSource.getOrderById is not a function 29 | 30 | const orders = await Promise.all( > 31 | orderIds.map(id => orderDataSource.getOrderById(id)) | ^ 32 | ); 33 | 34 | return orders; at src/resolvers/orderResolvers.js:31:42 at Array.map (<anonymous>) at DataLoader._batchLoadFn (src/resolvers/orderResolvers.js:31:16)
JavaScriptsrc/resolvers/orderResolvers.js示意Illustrative
1function createOrderLoader(orderDataSource) {
2 return new DataLoader(async orderIds => {
3 const orders = await Promise.all(
4 orderIds.map(id => orderDataSource.getOrderById(id))
5 );
6 return orders;
7 });
8}
9
10// 参考:OrderDataSource 上真实存在的方法
11// class OrderDataSource {
12// async getOrder(id) { ... }
13// async getOrdersByUserId(userId) { ... }
14// async createOrder(userId, items) { ... }
15// }
1function createOrderLoader(orderDataSource) {
2 return new DataLoader(async orderIds => {
3 const orders = await Promise.all(
4 orderIds.map(id => orderDataSource.getOrderById(id))
5 );
6 return orders;
7 });
8}
9
10// For reference: the methods OrderDataSource really has
11// class OrderDataSource {
12// async getOrder(id) { ... }
13// async getOrdersByUserId(userId) { ... }
14// async createOrder(userId, items) { ... }
15// }
第 2 步 · 这是什么类型的错误Step 2 · what kind of error is this
来自From TODO 1 · User.ordersTODO 1 · User.orders · Federation 考试Federation exam
L2填空Fill the blanks补全 User.ordersFill in User.orders

四个空。第 2 个是数据源上的真实方法名, 第 4 个是那行最容易漏的防御。

Four blanks. The second is the method name that really exists on the data source; the fourth is the guard people most often forget.

JSsrc/resolvers/orderResolvers.js4 个空4 blanks
1async orders(user, _, { dataSources, loaders, correlationId }) {
2 try {
3 console.log(`[${correlationId}] Resolving User.orders for userId: ${user.}`);
4
5 const orders = await dataSources.orderDataSource.(user.id);
6
7 return orders [];
8 } catch (error) {
9 if (error GraphQLError) throw error;
10
11 console.error(`[${correlationId}] Error:`, error.message);
12 throw new GraphQLError('Failed to fetch orders for user', {
13 extensions: { code: ErrorCodes.SERVICE_ERROR, correlationId }
14 });
15 }
16}
把 4 个空都填上才能检查(还差 4 个)Fill all 4 blanks to check (4 to go)
来自From TODO 2 · Order.shippingInfoTODO 2 · Order.shippingInfo · Federation 考试Federation exam
L2填空Fill the blanks补全 Order.shippingInfoFill in Order.shippingInfo

三个空。第 1 个决定你答不答得到 N+1 考点, 第 3 个决定第二条测试过不过。

Three blanks. The first decides whether you answer the N+1 question at all; the third decides whether the second test passes.

JSsrc/resolvers/orderResolvers.js3 个空3 blanks
1async shippingInfo(parent, _, { dataSources, loaders, correlationId }) {
2 try {
3 const shippingInfo = await .shippingInfoLoader.load(parent.);
4
5 return shippingInfo ?? ;
6 } catch (error) {
7 if (error instanceof GraphQLError) throw error;
8 console.error(`[${correlationId}] Error:`, error.message);
9 throw new GraphQLError('Failed to fetch shipping info', {
10 extensions: { code: ErrorCodes.SERVICE_ERROR, correlationId, orderId: parent.id }
11 });
12 }
13}
把 3 个空都填上才能检查(还差 3 个)Fill all 3 blanks to check (3 to go)
来自From TODO 3 & 4 · Query.order 与 Query.ordersTODO 3 & 4 · Query.order and Query.orders · Federation 考试Federation exam
L2填空Fill the blanks补全两个 Query resolverFill in both Query resolvers

四个空横跨两个 resolver。注意它们数据来源不同、兜底策略不同。

Four blanks across two resolvers. Note they read from different places and need different fallbacks.

JSsrc/resolvers/orderResolvers.js4 个空4 blanks
1// schema: order(id: ID!): Order (可空)
2async order(_, { id }, { dataSources, loaders, correlationId }) {
3 try {
4 const order = await loaders..load(id);
5
6 if (!order) {
7 throw new GraphQLError(`Order not found: ${id}`, {
8 extensions: { code: ErrorCodes., correlationId }
9 });
10 }
11 return order;
12 } catch (error) {
13 if (error instanceof GraphQLError) throw error;
14 throw new GraphQLError('Failed to fetch order', {
15 extensions: { code: ErrorCodes.SERVICE_ERROR, correlationId }
16 });
17 }
18}
19
20// schema: orders(userId: ID!): [Order!]! (双重非空)
21async orders(_, { }, { dataSources, correlationId }) {
22 try {
23 const orders = await dataSources.orderDataSource.getOrdersByUserId(userId);
24 return orders ?? ;
25 } catch (error) {
26 if (error instanceof GraphQLError) throw error;
27 throw new GraphQLError('Failed to fetch orders', {
28 extensions: { code: ErrorCodes.SERVICE_ERROR, correlationId }
29 });
30 }
31}
把 4 个空都填上才能检查(还差 4 个)Fill all 4 blanks to check (4 to go)
来自From 六个端点:状态码就是这道题的全部Six endpoints: the status codes are the whole task · Federation 考试Federation exam
L2填空Fill the blanks补全三个关键端点的状态码与调用Fill in the status codes and calls of three key endpoints

五个空。第 2、4、5 个是这道题真正的得分点。

Five blanks. Numbers 2, 4 and 5 are where the credit in this question actually is.

JAVAOrderController.java5 个空5 blanks
1@GetMapping("/api/orders/{id}")
2public ResponseEntity<Order> getOrderById(@PathVariable Long id) {
3 // 找不到时 service 抛 EntityNotFoundException,交给全局处理器
4 return ResponseEntity.(orderService.getOrderById(id));
5}
6
7@PostMapping("/api/orders")
8public ResponseEntity<Order> createOrder(@Valid @RequestBody CreateOrderRequest request) {
9 Order created = orderService.createOrder(request);
10 return ResponseEntity.status(HttpStatus.).body(created);
11}
12
13@PatchMapping("/api/orders/{id}/status")
14public ResponseEntity<Order> updateOrderStatus(
15 @PathVariable Long id,
16 @RequestBody Map<String, String> statusUpdate) {
17 String raw = statusUpdate.get("status");
18 if (raw == null || raw.isBlank()) {
19 throw new ResponseStatusException(HttpStatus., "status is required");
20 }
21 OrderStatus status = OrderStatus.(raw.trim().toUpperCase());
22 return ResponseEntity.ok(orderService.updateOrderStatus(id, status));
23}
24
25@DeleteMapping("/api/orders/{id}")
26public ResponseEntity<Void> deleteOrder(@PathVariable Long id) {
27 orderService.deleteOrder(id);
28 return ResponseEntity.().build();
29}
把 5 个空都填上才能检查(还差 5 个)Fill all 5 blanks to check (5 to go)
来自From Debug Lab · Federation 十种典型故障Debug Lab · ten common Federation failures · Federation 考试Federation exam
L2Debug LabDebug Lab故障 2 · Cannot return null for non-nullable fieldFault 2 · Cannot return null for non-nullable field

查一个没有订单的用户,整个 data 变成了null,而且 errors 里有一条很长的消息。

You query a user who has no orders, the whole data turns into null, and errors carries one very long message.

第 1 步 · 先看现象和代码,别急着改Step 1 · read the symptom and the code before you touch anything
$ node verify-schema.mjs Query.orders: {"orders":null} errors: [{ "message": "Cannot return null for non-nullable field Query.orders.", "path": ["orders"], "extensions": { "code": "INTERNAL_SERVER_ERROR" } }] # 更严重的情况:如果查询是嵌套的,整个 data 会变成 null$ node verify-schema.mjs Query.orders: {"orders":null} errors: [{ "message": "Cannot return null for non-nullable field Query.orders.", "path": ["orders"], "extensions": { "code": "INTERNAL_SERVER_ERROR" } }] # Worse case: if the query is nested, the whole data object turns into null
JavaScriptsrc/resolvers/orderResolvers.js示意Illustrative
1async orders(_, { userId }, { dataSources, correlationId }) {
2 const orders = await dataSources.orderDataSource.getOrdersByUserId(userId);
3 return orders; // 数据源可能返回 undefined
4}
5
6// 参考 schema.graphql:
7// type Query {
8// orders(userId: ID!): [Order!]! ← 双重非空
9// }
1async orders(_, { userId }, { dataSources, correlationId }) {
2 const orders = await dataSources.orderDataSource.getOrdersByUserId(userId);
3 return orders; // the data source may return undefined
4}
5
6// For reference, schema.graphql says:
7// type Query {
8// orders(userId: ID!): [Order!]! ← non-null twice
9// }
第 2 步 · 这是什么类型的错误Step 2 · what kind of error is this
来自From Debug Lab · Federation 十种典型故障Debug Lab · ten common Federation failures · Federation 考试Federation exam
L2Debug LabDebug Lab故障 4 · PATCH 传了小写状态,返回 500Fault 4 · PATCH sends a lowercase status and gets a 500

Java 那边。mvn test 全过, 但客户端传小写的 shipped 时服务返回 500。

This one is on the Java side. mvn test passes everything, but the service returns 500 when the client sends the lowercase shipped.

第 1 步 · 先看现象和代码,别急着改Step 1 · read the symptom and the code before you touch anything
$ curl -i -X PATCH localhost:8080/api/orders/1/status \ -H 'Content-Type: application/json' -d '{"status":"shipped"}' HTTP/1.1 500 {"timestamp":"...","status":500,"error":"Internal Server Error"} # 服务端日志: java.lang.IllegalArgumentException: No enum constant com.techflow.orders.model.OrderStatus.shipped at java.base/java.lang.Enum.valueOf(Enum.java:293) at com.techflow.orders.model.OrderStatus.valueOf(OrderStatus.java:3) at c.t.orders.controller.OrderController.updateOrderStatus(OrderController.java:71) # mvn test:Tests run: 5, Failures: 0 ← 测试全过$ curl -i -X PATCH localhost:8080/api/orders/1/status \ -H 'Content-Type: application/json' -d '{"status":"shipped"}' HTTP/1.1 500 {"timestamp":"...","status":500,"error":"Internal Server Error"} # Server log: java.lang.IllegalArgumentException: No enum constant com.techflow.orders.model.OrderStatus.shipped at java.base/java.lang.Enum.valueOf(Enum.java:293) at com.techflow.orders.model.OrderStatus.valueOf(OrderStatus.java:3) at c.t.orders.controller.OrderController.updateOrderStatus(OrderController.java:71) # mvn test: Tests run: 5, Failures: 0 ← every test passes
JavaOrderController.java示意Illustrative
1@PatchMapping("/api/orders/{id}/status")
2public ResponseEntity<Order> updateOrderStatus(
3 @PathVariable Long id,
4 @RequestBody Map<String, String> statusUpdate) {
5 OrderStatus status = OrderStatus.valueOf(statusUpdate.get("status"));
6 return ResponseEntity.ok(orderService.updateOrderStatus(id, status));
7}
第 2 步 · 这是什么类型的错误Step 2 · what kind of error is this