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
筛一下Filter theseFederation 考试Federation exam填空Fill the blanks
难度LevelL1 → L4 和上面四档同一个意思:给你的东西越来越少L1 → L4: the same idea as the four tiers above — less is handed to you全部难度All levelsL1L1L2L2L3L3L4L4

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

练习Exercises

筛出 8 个练习(共 148 个)。Showing 8 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 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)