@k2works/claude-code-booster 3.2.1 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/lib/assets/.claude/skills/analyzing-business/SKILL.md +2 -2
  2. package/lib/assets/.claude/skills/analyzing-inception-deck/SKILL.md +5 -5
  3. package/lib/assets/.claude/skills/analyzing-requirements/SKILL.md +2 -2
  4. package/lib/assets/.claude/skills/generating-slides/SKILL.md +7 -7
  5. package/lib/assets/docs/article/index.md +4 -1
  6. package/lib/assets/docs/article/practical-database-design/index.md +121 -0
  7. package/lib/assets/docs/article/practical-database-design/part1/chapter01.md +288 -0
  8. package/lib/assets/docs/article/practical-database-design/part1/chapter02.md +518 -0
  9. package/lib/assets/docs/article/practical-database-design/part1/chapter03.md +557 -0
  10. package/lib/assets/docs/article/practical-database-design/part2/chapter04.md +924 -0
  11. package/lib/assets/docs/article/practical-database-design/part2/chapter05.md +1627 -0
  12. package/lib/assets/docs/article/practical-database-design/part2/chapter06.md +2716 -0
  13. package/lib/assets/docs/article/practical-database-design/part2/chapter07.md +2082 -0
  14. package/lib/assets/docs/article/practical-database-design/part2/chapter08.md +2105 -0
  15. package/lib/assets/docs/article/practical-database-design/part2/chapter09.md +2031 -0
  16. package/lib/assets/docs/article/practical-database-design/part2/chapter10.md +1387 -0
  17. package/lib/assets/docs/article/practical-database-design/part2/chapter11.md +1677 -0
  18. package/lib/assets/docs/article/practical-database-design/part2/chapter12.md +1417 -0
  19. package/lib/assets/docs/article/practical-database-design/part2/chapter13.md +1434 -0
  20. package/lib/assets/docs/article/practical-database-design/part3/chapter14.md +667 -0
  21. package/lib/assets/docs/article/practical-database-design/part3/chapter15.md +1625 -0
  22. package/lib/assets/docs/article/practical-database-design/part3/chapter16.md +1915 -0
  23. package/lib/assets/docs/article/practical-database-design/part3/chapter17.md +1708 -0
  24. package/lib/assets/docs/article/practical-database-design/part3/chapter18.md +2095 -0
  25. package/lib/assets/docs/article/practical-database-design/part3/chapter19.md +1123 -0
  26. package/lib/assets/docs/article/practical-database-design/part3/chapter20.md +1031 -0
  27. package/lib/assets/docs/article/practical-database-design/part3/chapter21.md +1382 -0
  28. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter14-orm.md +991 -0
  29. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter15-orm.md +1300 -0
  30. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter16-orm.md +1166 -0
  31. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter17-orm.md +1584 -0
  32. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter18-orm.md +1183 -0
  33. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter19-orm.md +1016 -0
  34. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter20-orm.md +1753 -0
  35. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter21-orm.md +1447 -0
  36. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter22-orm.md +1878 -0
  37. package/lib/assets/docs/article/practical-database-design/part4/chapter22.md +965 -0
  38. package/lib/assets/docs/article/practical-database-design/part4/chapter23.md +2069 -0
  39. package/lib/assets/docs/article/practical-database-design/part4/chapter24.md +2439 -0
  40. package/lib/assets/docs/article/practical-database-design/part4/chapter25.md +3661 -0
  41. package/lib/assets/docs/article/practical-database-design/part4/chapter26.md +2916 -0
  42. package/lib/assets/docs/article/practical-database-design/part4/chapter27.md +3105 -0
  43. package/lib/assets/docs/article/practical-database-design/part4/chapter28.md +2697 -0
  44. package/lib/assets/docs/article/practical-database-design/part4/chapter29.md +2544 -0
  45. package/lib/assets/docs/article/practical-database-design/part4/chapter30.md +2180 -0
  46. package/lib/assets/docs/article/practical-database-design/part4/chapter31.md +1192 -0
  47. package/lib/assets/docs/article/practical-database-design/part4/chapter32.md +2101 -0
  48. package/lib/assets/docs/article/practical-database-design/part5/chapter33.md +1032 -0
  49. package/lib/assets/docs/article/practical-database-design/part5/chapter34.md +1609 -0
  50. package/lib/assets/docs/article/practical-database-design/part5/chapter35.md +1453 -0
  51. package/lib/assets/docs/article/practical-database-design/part5/chapter36.md +1292 -0
  52. package/lib/assets/docs/article/practical-database-design/part5/chapter37.md +1470 -0
  53. package/lib/assets/docs/article/practical-database-design/part5/chapter38.md +1698 -0
  54. package/lib/assets/docs/article/practical-database-design/part5/chapter39.md +2334 -0
  55. package/lib/assets/docs/article/practical-database-design/study/study2-1.md +1693 -0
  56. package/lib/assets/docs/article/practical-database-design/study/study2-2.md +1347 -0
  57. package/lib/assets/docs/article/practical-database-design/study/study2-3.md +2044 -0
  58. package/lib/assets/docs/article/practical-database-design/study/study2-4.md +2229 -0
  59. package/lib/assets/docs/article/practical-database-design/study/study2-5.md +2418 -0
  60. package/lib/assets/docs/article/practical-database-design/study/study3-1.md +2205 -0
  61. package/lib/assets/docs/article/practical-database-design/study/study3-2.md +2221 -0
  62. package/lib/assets/docs/article/practical-database-design/study/study3-3.md +2253 -0
  63. package/lib/assets/docs/article/practical-database-design/study/study3-4.md +2106 -0
  64. package/lib/assets/docs/article/practical-database-design/study/study3-5.md +2507 -0
  65. package/lib/assets/docs/article/practical-database-design/study/study4-1.md +2587 -0
  66. package/lib/assets/docs/article/practical-database-design/study/study4-2.md +2075 -0
  67. package/lib/assets/docs/article/practical-database-design/study/study4-3.md +1805 -0
  68. package/lib/assets/docs/article/practical-database-design/study/study4-4.md +1895 -0
  69. package/lib/assets/docs/article/practical-database-design/study/study4-5.md +2878 -0
  70. package/package.json +1 -1
@@ -0,0 +1,2229 @@
1
+ # 実践データベース設計:販売管理システム 研究 4 - GraphQL サービスの実装
2
+
3
+ ## はじめに
4
+
5
+ 本研究では、REST API(第10部-A)や gRPC(研究 3)とは異なるアプローチとして、**GraphQL** による販売管理システムを実装します。クライアントが必要なデータを正確に指定できる柔軟なクエリと、リアルタイム更新を実現する Subscription を活用します。
6
+
7
+ 研究 1 で構築したヘキサゴナルアーキテクチャ(ドメイン層・アプリケーション層)はそのまま共有し、**Input Adapter として GraphQL リゾルバ層のみを追加**します。
8
+
9
+ ---
10
+
11
+ ## 第14章:GraphQL サーバーの基礎
12
+
13
+ ### 14.1 GraphQL とは
14
+
15
+ GraphQL は Facebook が開発したクエリ言語および実行エンジンです。クライアントが必要なデータの形状を指定でき、Over-fetching(不要なデータの取得)や Under-fetching(必要なデータの不足)を防ぎます。
16
+
17
+ ```plantuml
18
+ @startuml graphql_architecture
19
+ !define RECTANGLE class
20
+
21
+ skinparam backgroundColor #FEFEFE
22
+
23
+ package "GraphQL Architecture (販売管理システム)" {
24
+
25
+ package "Client Side" {
26
+ RECTANGLE "GraphQL Client\n(Apollo/Relay/urql)" as client {
27
+ - Query (読み取り)
28
+ - Mutation (書き込み)
29
+ - Subscription (リアルタイム)
30
+ }
31
+ }
32
+
33
+ package "Server Side" {
34
+ RECTANGLE "GraphQL Server\n(Spring for GraphQL)" as server {
35
+ - ProductResolver
36
+ - PartnerResolver
37
+ - OrderResolver
38
+ - InvoiceResolver
39
+ }
40
+ }
41
+
42
+ package "Shared" {
43
+ RECTANGLE "GraphQL Schema\n(.graphqls files)" as schema {
44
+ - schema.graphqls
45
+ - product.graphqls
46
+ - partner.graphqls
47
+ - order.graphqls
48
+ }
49
+ }
50
+ }
51
+
52
+ client --> schema : "スキーマに基づいて\nクエリを構築"
53
+ server --> schema : "スキーマに基づいて\nリゾルバを実装"
54
+ client <--> server : "HTTP/WebSocket\n(JSON)"
55
+
56
+ note bottom of schema
57
+ スキーマ駆動開発
58
+ クライアント主導のデータ取得
59
+ 型安全な API
60
+ end note
61
+
62
+ @enduml
63
+ ```
64
+
65
+ **REST API / gRPC / GraphQL の比較:**
66
+
67
+ | 特徴 | REST API | gRPC | GraphQL |
68
+ |------|----------|------|---------|
69
+ | プロトコル | HTTP/1.1 | HTTP/2 | HTTP/1.1 or HTTP/2 |
70
+ | データ形式 | JSON | Protocol Buffers | JSON |
71
+ | スキーマ | OpenAPI (任意) | .proto (必須) | .graphqls (必須) |
72
+ | データ取得 | 固定レスポンス | 固定レスポンス | クライアント指定 |
73
+ | エンドポイント | 複数 | 複数 | 単一 |
74
+ | リアルタイム | WebSocket 別実装 | ストリーミング | Subscription |
75
+ | 主な用途 | 汎用 API | マイクロサービス | フロントエンド向け |
76
+
77
+ ---
78
+
79
+ ### 14.2 3つの操作タイプ
80
+
81
+ GraphQL は 3 つの操作タイプをサポートします:
82
+
83
+ ```plantuml
84
+ @startuml graphql_operations
85
+ skinparam backgroundColor #FEFEFE
86
+
87
+ rectangle "1. Query\n(読み取り)" as query #LightBlue {
88
+ }
89
+ note right of query
90
+ { products { code name price } }
91
+ → { products: [...] }
92
+
93
+ データの取得
94
+ 複数リソースを1回で取得可能
95
+ end note
96
+
97
+ rectangle "2. Mutation\n(書き込み)" as mutation #LightGreen {
98
+ }
99
+ note right of mutation
100
+ mutation { createOrder(...) }
101
+ → { createOrder: {...} }
102
+
103
+ データの作成・更新・削除
104
+ end note
105
+
106
+ rectangle "3. Subscription\n(リアルタイム)" as subscription #LightCoral {
107
+ }
108
+ note right of subscription
109
+ subscription { orderStatusChanged }
110
+ → (WebSocket でプッシュ通知)
111
+
112
+ リアルタイム更新の受信
113
+ end note
114
+
115
+ query -[hidden]-> mutation
116
+ mutation -[hidden]-> subscription
117
+
118
+ @enduml
119
+ ```
120
+
121
+ **用途:**
122
+
123
+ 1. **Query**: データ取得(商品一覧、受注明細、在庫照会)
124
+ 2. **Mutation**: データ更新(受注登録、出荷確定、入金処理)
125
+ 3. **Subscription**: リアルタイム通知(受注ステータス変更、在庫変動)
126
+
127
+ ---
128
+
129
+ ### 14.3 GraphQL におけるヘキサゴナルアーキテクチャ
130
+
131
+ GraphQL を導入しても、既存のヘキサゴナルアーキテクチャ(ドメイン層・アプリケーション層)はそのまま共有し、**Input Adapter として GraphQL リゾルバ層のみを追加**します。
132
+
133
+ ```plantuml
134
+ @startuml hexagonal_graphql
135
+ !define RECTANGLE class
136
+
137
+ package "Hexagonal Architecture (GraphQL版)" {
138
+
139
+ RECTANGLE "Application Core\n(Domain + Use Cases)" as core {
140
+ - Product (商品)
141
+ - Partner (取引先)
142
+ - Order (受注)
143
+ - Shipment (出荷)
144
+ - Invoice (請求)
145
+ - ProductUseCase
146
+ - OrderUseCase
147
+ - InvoiceUseCase
148
+ }
149
+
150
+ RECTANGLE "Input Adapters\n(Driving Side)" as input {
151
+ - REST Controller(既存)
152
+ - gRPC Service(既存)
153
+ - GraphQL Resolver(新規追加)
154
+ - DataFetcher
155
+ - DataLoader
156
+ }
157
+
158
+ RECTANGLE "Output Adapters\n(Driven Side)" as output {
159
+ - MyBatis Repository
160
+ - Database Access
161
+ - Entity Mapping
162
+ }
163
+ }
164
+
165
+ input --> core : "Input Ports\n(Use Cases)"
166
+ core --> output : "Output Ports\n(Repository Interfaces)"
167
+
168
+ note top of core
169
+ 既存のビジネスロジック
170
+ REST API / gRPC 版と完全に共有
171
+ GraphQL 固有のコードは含まない
172
+ end note
173
+
174
+ note left of input
175
+ GraphQL リゾルバを
176
+ Input Adapter として追加
177
+ 既存の REST/gRPC と共存可能
178
+ end note
179
+
180
+ @enduml
181
+ ```
182
+
183
+ **GraphQL でもヘキサゴナルアーキテクチャを維持する理由:**
184
+
185
+ 1. **再利用性**: 既存の UseCase/Repository をそのまま活用
186
+ 2. **並行運用**: REST API、gRPC、GraphQL を同時提供可能
187
+ 3. **テスト容易性**: ドメインロジックは通信プロトコルに依存しない
188
+ 4. **移行容易性**: 段階的に API 形式を追加・変更可能
189
+
190
+ ---
191
+
192
+ ### 14.4 ディレクトリ構成
193
+
194
+ 既存の構成に `infrastructure/graphql/` を追加するだけです。
195
+
196
+ <details>
197
+ <summary>コード例: ディレクトリ構成</summary>
198
+
199
+ ```
200
+ src/main/java/com/example/sales/
201
+ ├── domain/ # ドメイン層(API版と共通)
202
+ │ ├── model/
203
+ │ │ ├── product/
204
+ │ │ ├── partner/
205
+ │ │ ├── order/
206
+ │ │ ├── shipment/
207
+ │ │ └── invoice/
208
+ │ └── exception/
209
+
210
+ ├── application/ # アプリケーション層(API版と共通)
211
+ │ ├── port/
212
+ │ │ ├── in/ # Input Port(ユースケース)
213
+ │ │ └── out/ # Output Port(リポジトリ)
214
+ │ └── service/
215
+
216
+ ├── infrastructure/
217
+ │ ├── persistence/ # Output Adapter(DB実装)- 既存
218
+ │ │ ├── mapper/
219
+ │ │ └── repository/
220
+ │ ├── rest/ # Input Adapter(REST実装)- 既存
221
+ │ ├── grpc/ # Input Adapter(gRPC実装)- 既存
222
+ │ └── graphql/ # Input Adapter(GraphQL実装)- 新規追加
223
+ │ ├── resolver/ # Query/Mutation リゾルバ
224
+ │ ├── dataloader/ # N+1 問題対策
225
+ │ ├── scalar/ # カスタムスカラー型
226
+ │ └── subscription/ # Subscription ハンドラ
227
+
228
+ ├── config/
229
+
230
+ └── src/main/resources/
231
+ └── graphql/ # GraphQL スキーマ定義
232
+ ├── schema.graphqls
233
+ ├── product.graphqls
234
+ ├── partner.graphqls
235
+ ├── order.graphqls
236
+ ├── shipment.graphqls
237
+ └── invoice.graphqls
238
+ ```
239
+
240
+ </details>
241
+
242
+ ---
243
+
244
+ ### 14.5 技術スタックの追加
245
+
246
+ 既存の `build.gradle.kts` に GraphQL 関連の依存関係を追加します。
247
+
248
+ #### build.gradle.kts(差分)
249
+
250
+ <details>
251
+ <summary>コード例: build.gradle.kts</summary>
252
+
253
+ ```kotlin
254
+ dependencies {
255
+ // 既存の依存関係(Spring Boot, MyBatis, PostgreSQL等)はそのまま
256
+
257
+ // GraphQL 関連を追加
258
+ implementation("org.springframework.boot:spring-boot-starter-graphql")
259
+ implementation("org.springframework.boot:spring-boot-starter-websocket") // Subscription 用
260
+
261
+ // GraphQL 拡張
262
+ implementation("com.graphql-java:graphql-java-extended-scalars:21.0")
263
+
264
+ // Test
265
+ testImplementation("org.springframework.graphql:spring-graphql-test")
266
+ }
267
+ ```
268
+
269
+ </details>
270
+
271
+ **追加パッケージの説明:**
272
+
273
+ | パッケージ | 用途 |
274
+ |-----------|------|
275
+ | spring-boot-starter-graphql | Spring Boot GraphQL 統合 |
276
+ | spring-boot-starter-websocket | Subscription (WebSocket) |
277
+ | graphql-java-extended-scalars | DateTime, BigDecimal 等のスカラー型 |
278
+ | spring-graphql-test | GraphQL テストサポート |
279
+
280
+ #### application.yml(差分)
281
+
282
+ <details>
283
+ <summary>コード例: application.yml</summary>
284
+
285
+ ```yaml
286
+ spring:
287
+ graphql:
288
+ graphiql:
289
+ enabled: true
290
+ path: /graphiql
291
+ websocket:
292
+ path: /graphql
293
+ connection-init-timeout: 60s
294
+ keep-alive:
295
+ enabled: true
296
+ interval: 30s
297
+ schema:
298
+ printer:
299
+ enabled: true
300
+ locations:
301
+ - classpath:graphql/
302
+ cors:
303
+ allowed-origins: "*"
304
+ allowed-methods: GET, POST
305
+ ```
306
+
307
+ </details>
308
+
309
+ ---
310
+
311
+ ### 14.6 GraphQL 設定クラス
312
+
313
+ <details>
314
+ <summary>コード例: GraphQLConfig.java</summary>
315
+
316
+ ```java
317
+ package com.example.sales.config;
318
+
319
+ import graphql.scalars.ExtendedScalars;
320
+ import org.springframework.context.annotation.Bean;
321
+ import org.springframework.context.annotation.Configuration;
322
+ import org.springframework.graphql.execution.RuntimeWiringConfigurer;
323
+
324
+ /**
325
+ * GraphQL 設定
326
+ */
327
+ @Configuration
328
+ public class GraphQLConfig {
329
+
330
+ @Bean
331
+ public RuntimeWiringConfigurer runtimeWiringConfigurer() {
332
+ return wiringBuilder -> wiringBuilder
333
+ .scalar(ExtendedScalars.Date)
334
+ .scalar(ExtendedScalars.DateTime)
335
+ .scalar(ExtendedScalars.GraphQLBigDecimal)
336
+ .scalar(ExtendedScalars.GraphQLLong);
337
+ }
338
+ }
339
+ ```
340
+
341
+ </details>
342
+
343
+ ---
344
+
345
+ ### 14.7 GraphQL スキーマ定義
346
+
347
+ #### src/main/resources/graphql/schema.graphqls
348
+
349
+ <details>
350
+ <summary>コード例: schema.graphqls</summary>
351
+
352
+ ```graphql
353
+ # ルートスキーマ
354
+ type Query {
355
+ # 商品
356
+ product(productCode: ID!): Product
357
+ products(category: ProductCategory, page: Int, size: Int): ProductConnection!
358
+
359
+ # 取引先
360
+ partner(partnerCode: ID!): Partner
361
+ partners(type: PartnerType, page: Int, size: Int): PartnerConnection!
362
+
363
+ # 倉庫
364
+ warehouse(warehouseCode: ID!): Warehouse
365
+ warehouses(page: Int, size: Int): WarehouseConnection!
366
+
367
+ # 受注
368
+ order(orderNumber: ID!): Order
369
+ orders(status: OrderStatus, partnerCode: ID, page: Int, size: Int): OrderConnection!
370
+
371
+ # 出荷
372
+ shipment(shipmentNumber: ID!): Shipment
373
+ shipments(status: ShipmentStatus, page: Int, size: Int): ShipmentConnection!
374
+
375
+ # 請求
376
+ invoice(invoiceNumber: ID!): Invoice
377
+ invoices(status: InvoiceStatus, partnerCode: ID, page: Int, size: Int): InvoiceConnection!
378
+ }
379
+
380
+ type Mutation {
381
+ # 商品
382
+ createProduct(input: CreateProductInput!): Product!
383
+ updateProduct(input: UpdateProductInput!): Product!
384
+ deleteProduct(productCode: ID!): Boolean!
385
+
386
+ # 取引先
387
+ createPartner(input: CreatePartnerInput!): Partner!
388
+ updatePartner(input: UpdatePartnerInput!): Partner!
389
+
390
+ # 受注
391
+ createOrder(input: CreateOrderInput!): Order!
392
+ confirmOrder(orderNumber: ID!): Order!
393
+ cancelOrder(orderNumber: ID!, reason: String): Order!
394
+
395
+ # 出荷
396
+ createShipment(input: CreateShipmentInput!): Shipment!
397
+ startPicking(shipmentNumber: ID!): Shipment!
398
+ confirmShipment(shipmentNumber: ID!): Shipment!
399
+
400
+ # 請求
401
+ executeClosing(input: ExecuteClosingInput!): ClosingResult!
402
+ issueInvoice(invoiceNumber: ID!): Invoice!
403
+ recordReceipt(input: RecordReceiptInput!): Receipt!
404
+ }
405
+
406
+ type Subscription {
407
+ # 受注ステータス変更
408
+ orderStatusChanged(orderNumber: ID): OrderStatusChange!
409
+
410
+ # 出荷進捗
411
+ shipmentProgressUpdated(shipmentNumber: ID): ShipmentProgress!
412
+
413
+ # 在庫変動
414
+ inventoryChanged(warehouseCode: ID, productCode: ID): InventoryChange!
415
+
416
+ # 締処理進捗
417
+ closingProgressUpdated(closingId: ID!): ClosingProgress!
418
+ }
419
+
420
+ # ページネーション共通型
421
+ type PageInfo {
422
+ hasNextPage: Boolean!
423
+ hasPreviousPage: Boolean!
424
+ totalElements: Int!
425
+ totalPages: Int!
426
+ currentPage: Int!
427
+ }
428
+
429
+ # カスタムスカラー
430
+ scalar Date
431
+ scalar DateTime
432
+ scalar BigDecimal
433
+ scalar Long
434
+ ```
435
+
436
+ </details>
437
+
438
+ #### src/main/resources/graphql/product.graphqls
439
+
440
+ <details>
441
+ <summary>コード例: product.graphqls</summary>
442
+
443
+ ```graphql
444
+ # 商品区分
445
+ enum ProductCategory {
446
+ PRODUCT # 製品
447
+ MATERIAL # 原材料
448
+ PART # 部品
449
+ }
450
+
451
+ # 税区分
452
+ enum TaxCategory {
453
+ TAXABLE # 課税
454
+ TAX_EXEMPT # 非課税
455
+ TAX_FREE # 免税
456
+ }
457
+
458
+ # 商品
459
+ type Product {
460
+ productCode: ID!
461
+ productName: String!
462
+ productNameKana: String
463
+ category: ProductCategory!
464
+ taxCategory: TaxCategory!
465
+ unitCode: String
466
+ sellingPrice: BigDecimal!
467
+ purchasePrice: BigDecimal
468
+ costPrice: BigDecimal
469
+ safetyStock: Int
470
+ reorderPoint: Int
471
+ isActive: Boolean!
472
+ createdAt: DateTime!
473
+ updatedAt: DateTime!
474
+
475
+ # 関連データ(必要な場合のみ取得)
476
+ inventories: [Inventory!]!
477
+ classifications: [ProductClassification!]!
478
+ customerPrices: [CustomerPrice!]!
479
+ }
480
+
481
+ # 商品一覧(ページネーション付き)
482
+ type ProductConnection {
483
+ edges: [ProductEdge!]!
484
+ pageInfo: PageInfo!
485
+ }
486
+
487
+ type ProductEdge {
488
+ node: Product!
489
+ cursor: String!
490
+ }
491
+
492
+ # 入力型
493
+ input CreateProductInput {
494
+ productCode: ID!
495
+ productName: String!
496
+ productNameKana: String
497
+ category: ProductCategory!
498
+ taxCategory: TaxCategory!
499
+ unitCode: String
500
+ sellingPrice: BigDecimal!
501
+ purchasePrice: BigDecimal
502
+ costPrice: BigDecimal
503
+ safetyStock: Int
504
+ reorderPoint: Int
505
+ }
506
+
507
+ input UpdateProductInput {
508
+ productCode: ID!
509
+ productName: String
510
+ category: ProductCategory
511
+ taxCategory: TaxCategory
512
+ sellingPrice: BigDecimal
513
+ isActive: Boolean
514
+ }
515
+ ```
516
+
517
+ </details>
518
+
519
+ #### src/main/resources/graphql/order.graphqls
520
+
521
+ <details>
522
+ <summary>コード例: order.graphqls</summary>
523
+
524
+ ```graphql
525
+ # 受注ステータス
526
+ enum OrderStatus {
527
+ DRAFT # 仮登録
528
+ CONFIRMED # 確定
529
+ SHIPPED # 出荷済
530
+ CANCELLED # キャンセル
531
+ }
532
+
533
+ # 受注
534
+ type Order {
535
+ orderNumber: ID!
536
+ partnerCode: ID!
537
+ orderDate: Date!
538
+ deliveryDate: Date!
539
+ warehouseCode: ID!
540
+ status: OrderStatus!
541
+ totalAmount: BigDecimal!
542
+ taxAmount: BigDecimal!
543
+ grandTotal: BigDecimal!
544
+ salesPersonCode: String
545
+ remarks: String
546
+ createdAt: DateTime!
547
+ updatedAt: DateTime!
548
+
549
+ # 関連データ
550
+ partner: Partner!
551
+ warehouse: Warehouse!
552
+ details: [OrderDetail!]!
553
+ shipments: [Shipment!]!
554
+ }
555
+
556
+ # 受注明細
557
+ type OrderDetail {
558
+ orderNumber: ID!
559
+ lineNumber: Int!
560
+ productCode: ID!
561
+ quantity: Int!
562
+ unitPrice: BigDecimal!
563
+ amount: BigDecimal!
564
+ taxCategory: TaxCategory!
565
+ deliveryDate: Date
566
+ remarks: String
567
+
568
+ # 関連データ
569
+ product: Product!
570
+ }
571
+
572
+ # 受注ステータス変更イベント
573
+ type OrderStatusChange {
574
+ orderNumber: ID!
575
+ previousStatus: OrderStatus!
576
+ currentStatus: OrderStatus!
577
+ changedBy: String
578
+ changedAt: DateTime!
579
+ reason: String
580
+ }
581
+
582
+ # 入力型
583
+ input CreateOrderInput {
584
+ partnerCode: ID!
585
+ orderDate: Date!
586
+ deliveryDate: Date!
587
+ warehouseCode: ID!
588
+ salesPersonCode: String
589
+ remarks: String
590
+ details: [OrderDetailInput!]!
591
+ }
592
+
593
+ input OrderDetailInput {
594
+ productCode: ID!
595
+ quantity: Int!
596
+ unitPrice: BigDecimal
597
+ deliveryDate: Date
598
+ remarks: String
599
+ }
600
+ ```
601
+
602
+ </details>
603
+
604
+ ---
605
+
606
+ ### 14.8 基本的なリゾルバの実装
607
+
608
+ #### Query リゾルバ
609
+
610
+ <details>
611
+ <summary>コード例: QueryResolver.java</summary>
612
+
613
+ ```java
614
+ package com.example.sales.infrastructure.graphql.resolver;
615
+
616
+ import com.example.sales.application.port.in.ProductUseCase;
617
+ import com.example.sales.application.port.in.PartnerUseCase;
618
+ import com.example.sales.domain.model.product.Product;
619
+ import com.example.sales.domain.model.partner.Partner;
620
+ import com.example.sales.infrastructure.graphql.dto.*;
621
+ import org.springframework.graphql.data.method.annotation.Argument;
622
+ import org.springframework.graphql.data.method.annotation.QueryMapping;
623
+ import org.springframework.stereotype.Controller;
624
+
625
+ import java.util.List;
626
+
627
+ /**
628
+ * GraphQL Query リゾルバ
629
+ */
630
+ @Controller
631
+ public class QueryResolver {
632
+
633
+ private final ProductUseCase productUseCase;
634
+ private final PartnerUseCase partnerUseCase;
635
+
636
+ public QueryResolver(ProductUseCase productUseCase, PartnerUseCase partnerUseCase) {
637
+ this.productUseCase = productUseCase;
638
+ this.partnerUseCase = partnerUseCase;
639
+ }
640
+
641
+ // === 商品 ===
642
+
643
+ @QueryMapping
644
+ public Product product(@Argument String productCode) {
645
+ return productUseCase.findByCode(productCode).orElse(null);
646
+ }
647
+
648
+ @QueryMapping
649
+ public ProductConnection products(
650
+ @Argument String category,
651
+ @Argument Integer page,
652
+ @Argument Integer size) {
653
+
654
+ int pageNum = page != null ? page : 0;
655
+ int pageSize = size != null ? size : 20;
656
+
657
+ List<Product> products = productUseCase.findAll(category, pageNum, pageSize);
658
+ long totalCount = productUseCase.count(category);
659
+
660
+ return ProductConnection.of(products, pageNum, pageSize, totalCount);
661
+ }
662
+
663
+ // === 取引先 ===
664
+
665
+ @QueryMapping
666
+ public Partner partner(@Argument String partnerCode) {
667
+ return partnerUseCase.findByCode(partnerCode).orElse(null);
668
+ }
669
+
670
+ @QueryMapping
671
+ public PartnerConnection partners(
672
+ @Argument String type,
673
+ @Argument Integer page,
674
+ @Argument Integer size) {
675
+
676
+ int pageNum = page != null ? page : 0;
677
+ int pageSize = size != null ? size : 20;
678
+
679
+ List<Partner> partners = partnerUseCase.findAll(type, pageNum, pageSize);
680
+ long totalCount = partnerUseCase.count(type);
681
+
682
+ return PartnerConnection.of(partners, pageNum, pageSize, totalCount);
683
+ }
684
+ }
685
+ ```
686
+
687
+ </details>
688
+
689
+ #### Connection DTO(ページネーション)
690
+
691
+ <details>
692
+ <summary>コード例: ProductConnection.java</summary>
693
+
694
+ ```java
695
+ package com.example.sales.infrastructure.graphql.dto;
696
+
697
+ import com.example.sales.domain.model.product.Product;
698
+
699
+ import java.util.Base64;
700
+ import java.util.List;
701
+
702
+ /**
703
+ * 商品ページネーション結果(Connection パターン)
704
+ */
705
+ public record ProductConnection(
706
+ List<ProductEdge> edges,
707
+ PageInfo pageInfo
708
+ ) {
709
+ public static ProductConnection of(
710
+ List<Product> products,
711
+ int page,
712
+ int size,
713
+ long totalCount) {
714
+
715
+ List<ProductEdge> edges = products.stream()
716
+ .map(product -> new ProductEdge(
717
+ product,
718
+ encodeCursor(product.getProductCode())
719
+ ))
720
+ .toList();
721
+
722
+ int totalPages = (int) Math.ceil((double) totalCount / size);
723
+
724
+ PageInfo pageInfo = new PageInfo(
725
+ page < totalPages - 1, // hasNextPage
726
+ page > 0, // hasPreviousPage
727
+ totalCount,
728
+ totalPages,
729
+ page
730
+ );
731
+
732
+ return new ProductConnection(edges, pageInfo);
733
+ }
734
+
735
+ private static String encodeCursor(String productCode) {
736
+ return Base64.getEncoder().encodeToString(productCode.getBytes());
737
+ }
738
+ }
739
+
740
+ public record ProductEdge(
741
+ Product node,
742
+ String cursor
743
+ ) {}
744
+
745
+ public record PageInfo(
746
+ boolean hasNextPage,
747
+ boolean hasPreviousPage,
748
+ long totalElements,
749
+ int totalPages,
750
+ int currentPage
751
+ ) {}
752
+ ```
753
+
754
+ </details>
755
+
756
+ ---
757
+
758
+ ### 14.9 Spring for GraphQL の統合テスト
759
+
760
+ <details>
761
+ <summary>コード例: QueryResolverTest.java</summary>
762
+
763
+ ```java
764
+ package com.example.sales.infrastructure.graphql;
765
+
766
+ import org.junit.jupiter.api.Test;
767
+ import org.springframework.beans.factory.annotation.Autowired;
768
+ import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureHttpGraphQlTester;
769
+ import org.springframework.boot.test.context.SpringBootTest;
770
+ import org.springframework.graphql.test.tester.HttpGraphQlTester;
771
+ import org.springframework.test.context.DynamicPropertyRegistry;
772
+ import org.springframework.test.context.DynamicPropertySource;
773
+ import org.testcontainers.containers.PostgreSQLContainer;
774
+ import org.testcontainers.junit.jupiter.Container;
775
+ import org.testcontainers.junit.jupiter.Testcontainers;
776
+
777
+ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
778
+ @AutoConfigureHttpGraphQlTester
779
+ @Testcontainers
780
+ class QueryResolverTest {
781
+
782
+ @Container
783
+ static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
784
+
785
+ @DynamicPropertySource
786
+ static void configureProperties(DynamicPropertyRegistry registry) {
787
+ registry.add("spring.datasource.url", postgres::getJdbcUrl);
788
+ registry.add("spring.datasource.username", postgres::getUsername);
789
+ registry.add("spring.datasource.password", postgres::getPassword);
790
+ }
791
+
792
+ @Autowired
793
+ private HttpGraphQlTester graphQlTester;
794
+
795
+ @Test
796
+ void testQueryProduct() {
797
+ // language=GraphQL
798
+ String query = """
799
+ query {
800
+ product(productCode: "PRD001") {
801
+ productCode
802
+ productName
803
+ sellingPrice
804
+ category
805
+ }
806
+ }
807
+ """;
808
+
809
+ graphQlTester.document(query)
810
+ .execute()
811
+ .path("product.productCode")
812
+ .entity(String.class)
813
+ .isEqualTo("PRD001");
814
+ }
815
+
816
+ @Test
817
+ void testQueryProducts() {
818
+ // language=GraphQL
819
+ String query = """
820
+ query {
821
+ products(category: PRODUCT, page: 0, size: 10) {
822
+ edges {
823
+ node {
824
+ productCode
825
+ productName
826
+ }
827
+ cursor
828
+ }
829
+ pageInfo {
830
+ hasNextPage
831
+ totalElements
832
+ }
833
+ }
834
+ }
835
+ """;
836
+
837
+ graphQlTester.document(query)
838
+ .execute()
839
+ .path("products.edges")
840
+ .entityList(Object.class)
841
+ .hasSizeGreaterThan(0);
842
+ }
843
+
844
+ @Test
845
+ void testQueryProductWithRelations() {
846
+ // 関連データも含めて取得
847
+ // language=GraphQL
848
+ String query = """
849
+ query {
850
+ product(productCode: "PRD001") {
851
+ productCode
852
+ productName
853
+ inventories {
854
+ warehouseCode
855
+ quantity
856
+ availableQuantity
857
+ }
858
+ classifications {
859
+ classificationCode
860
+ classificationName
861
+ }
862
+ }
863
+ }
864
+ """;
865
+
866
+ graphQlTester.document(query)
867
+ .execute()
868
+ .path("product.productCode")
869
+ .entity(String.class)
870
+ .isEqualTo("PRD001");
871
+ }
872
+ }
873
+ ```
874
+
875
+ </details>
876
+
877
+ ---
878
+
879
+ ## 第15章:マスタ API の実装
880
+
881
+ ### 15.1 N+1 問題とは
882
+
883
+ GraphQL では、ネストしたデータを取得する際に **N+1 問題** が発生しやすくなります。例えば、10件の商品を取得し、それぞれの在庫情報を取得すると、1回(商品一覧)+ 10回(各商品の在庫)= 11回のクエリが実行されます。
884
+
885
+ ```plantuml
886
+ @startuml n_plus_1_problem
887
+
888
+ title N+1 問題の発生パターン
889
+
890
+ participant "GraphQL Client" as client
891
+ participant "ProductResolver" as resolver
892
+ participant "InventoryRepository" as repo
893
+ database "PostgreSQL" as db
894
+
895
+ client -> resolver : products(first: 10)
896
+ resolver -> db : SELECT * FROM 商品マスタ LIMIT 10
897
+ db --> resolver : 10件の商品
898
+
899
+ loop 各商品に対して(N回)
900
+ resolver -> repo : findByProductCode(code)
901
+ repo -> db : SELECT * FROM 在庫データ WHERE 商品コード = ?
902
+ db --> repo : 在庫データ
903
+ repo --> resolver : 在庫
904
+ end
905
+
906
+ resolver --> client : 商品一覧(在庫付き)
907
+
908
+ note right of db
909
+ 合計 11回のクエリ
910
+ (1 + N = 1 + 10)
911
+
912
+ 商品が100件なら101回!
913
+ end note
914
+
915
+ @enduml
916
+ ```
917
+
918
+ ---
919
+
920
+ ### 15.2 DataLoader による解決
921
+
922
+ **DataLoader** は、複数の個別リクエストをバッチ処理にまとめることで N+1 問題を解決します。
923
+
924
+ ```plantuml
925
+ @startuml dataloader_solution
926
+
927
+ title DataLoader による N+1 問題の解決
928
+
929
+ participant "GraphQL Client" as client
930
+ participant "ProductResolver" as resolver
931
+ participant "InventoryDataLoader" as loader
932
+ participant "InventoryRepository" as repo
933
+ database "PostgreSQL" as db
934
+
935
+ client -> resolver : products(first: 10)
936
+ resolver -> db : SELECT * FROM 商品マスタ LIMIT 10
937
+ db --> resolver : 10件の商品
938
+
939
+ loop 各商品に対して
940
+ resolver -> loader : load(productCode)
941
+ note right of loader : キューに追加
942
+ end
943
+
944
+ loader -> repo : loadMany([code1, code2, ...code10])
945
+ repo -> db : SELECT * FROM 在庫データ WHERE 商品コード IN (?, ?, ..., ?)
946
+ db --> repo : 10件の在庫データ
947
+ repo --> loader : Map<商品コード, 在庫>
948
+ loader --> resolver : 各商品の在庫
949
+
950
+ resolver --> client : 商品一覧(在庫付き)
951
+
952
+ note right of db
953
+ 合計 2回のクエリ
954
+ (1 + 1 = 2)
955
+
956
+ 商品が100件でも2回!
957
+ end note
958
+
959
+ @enduml
960
+ ```
961
+
962
+ ---
963
+
964
+ ### 15.3 DataLoader の実装
965
+
966
+ #### 在庫 DataLoader
967
+
968
+ <details>
969
+ <summary>コード例: InventoryDataLoader.java</summary>
970
+
971
+ ```java
972
+ package com.example.sales.infrastructure.graphql.dataloader;
973
+
974
+ import com.example.sales.application.port.out.InventoryRepository;
975
+ import com.example.sales.domain.model.inventory.Inventory;
976
+ import org.dataloader.BatchLoaderEnvironment;
977
+ import org.dataloader.MappedBatchLoader;
978
+ import org.springframework.stereotype.Component;
979
+
980
+ import java.util.List;
981
+ import java.util.Map;
982
+ import java.util.Set;
983
+ import java.util.concurrent.CompletableFuture;
984
+ import java.util.concurrent.CompletionStage;
985
+ import java.util.stream.Collectors;
986
+
987
+ /**
988
+ * 在庫データの DataLoader
989
+ * 商品コードをキーにバッチ取得
990
+ */
991
+ @Component
992
+ public class InventoryDataLoader implements MappedBatchLoader<String, List<Inventory>> {
993
+
994
+ private final InventoryRepository inventoryRepository;
995
+
996
+ public InventoryDataLoader(InventoryRepository inventoryRepository) {
997
+ this.inventoryRepository = inventoryRepository;
998
+ }
999
+
1000
+ @Override
1001
+ public CompletionStage<Map<String, List<Inventory>>> load(
1002
+ Set<String> productCodes,
1003
+ BatchLoaderEnvironment environment) {
1004
+
1005
+ return CompletableFuture.supplyAsync(() -> {
1006
+ // 一括取得
1007
+ List<Inventory> inventories = inventoryRepository
1008
+ .findByProductCodes(productCodes);
1009
+
1010
+ // 商品コードでグループ化
1011
+ return inventories.stream()
1012
+ .collect(Collectors.groupingBy(Inventory::getProductCode));
1013
+ });
1014
+ }
1015
+ }
1016
+ ```
1017
+
1018
+ </details>
1019
+
1020
+ #### 取引先 DataLoader
1021
+
1022
+ <details>
1023
+ <summary>コード例: PartnerDataLoader.java</summary>
1024
+
1025
+ ```java
1026
+ package com.example.sales.infrastructure.graphql.dataloader;
1027
+
1028
+ import com.example.sales.application.port.out.PartnerRepository;
1029
+ import com.example.sales.domain.model.partner.Partner;
1030
+ import org.dataloader.BatchLoaderEnvironment;
1031
+ import org.dataloader.MappedBatchLoader;
1032
+ import org.springframework.stereotype.Component;
1033
+
1034
+ import java.util.Map;
1035
+ import java.util.Set;
1036
+ import java.util.concurrent.CompletableFuture;
1037
+ import java.util.concurrent.CompletionStage;
1038
+ import java.util.function.Function;
1039
+ import java.util.stream.Collectors;
1040
+
1041
+ /**
1042
+ * 取引先データの DataLoader
1043
+ */
1044
+ @Component
1045
+ public class PartnerDataLoader implements MappedBatchLoader<String, Partner> {
1046
+
1047
+ private final PartnerRepository partnerRepository;
1048
+
1049
+ public PartnerDataLoader(PartnerRepository partnerRepository) {
1050
+ this.partnerRepository = partnerRepository;
1051
+ }
1052
+
1053
+ @Override
1054
+ public CompletionStage<Map<String, Partner>> load(
1055
+ Set<String> partnerCodes,
1056
+ BatchLoaderEnvironment environment) {
1057
+
1058
+ return CompletableFuture.supplyAsync(() -> {
1059
+ return partnerRepository.findByCodes(partnerCodes).stream()
1060
+ .collect(Collectors.toMap(
1061
+ Partner::getPartnerCode,
1062
+ Function.identity()
1063
+ ));
1064
+ });
1065
+ }
1066
+ }
1067
+ ```
1068
+
1069
+ </details>
1070
+
1071
+ ---
1072
+
1073
+ ### 15.4 DataLoader の登録
1074
+
1075
+ <details>
1076
+ <summary>コード例: DataLoaderConfig.java</summary>
1077
+
1078
+ ```java
1079
+ package com.example.sales.config;
1080
+
1081
+ import com.example.sales.infrastructure.graphql.dataloader.*;
1082
+ import org.dataloader.DataLoader;
1083
+ import org.dataloader.DataLoaderOptions;
1084
+ import org.dataloader.DataLoaderRegistry;
1085
+ import org.springframework.context.annotation.Bean;
1086
+ import org.springframework.context.annotation.Configuration;
1087
+ import org.springframework.graphql.execution.BatchLoaderRegistry;
1088
+
1089
+ /**
1090
+ * DataLoader 設定
1091
+ */
1092
+ @Configuration
1093
+ public class DataLoaderConfig {
1094
+
1095
+ public static final String INVENTORY_LOADER = "inventoryLoader";
1096
+ public static final String PARTNER_LOADER = "partnerLoader";
1097
+ public static final String PRODUCT_LOADER = "productLoader";
1098
+ public static final String WAREHOUSE_LOADER = "warehouseLoader";
1099
+
1100
+ private final InventoryDataLoader inventoryDataLoader;
1101
+ private final PartnerDataLoader partnerDataLoader;
1102
+ private final ProductDataLoader productDataLoader;
1103
+ private final WarehouseDataLoader warehouseDataLoader;
1104
+
1105
+ public DataLoaderConfig(
1106
+ InventoryDataLoader inventoryDataLoader,
1107
+ PartnerDataLoader partnerDataLoader,
1108
+ ProductDataLoader productDataLoader,
1109
+ WarehouseDataLoader warehouseDataLoader) {
1110
+ this.inventoryDataLoader = inventoryDataLoader;
1111
+ this.partnerDataLoader = partnerDataLoader;
1112
+ this.productDataLoader = productDataLoader;
1113
+ this.warehouseDataLoader = warehouseDataLoader;
1114
+ }
1115
+
1116
+ @Bean
1117
+ public BatchLoaderRegistry batchLoaderRegistry() {
1118
+ return new BatchLoaderRegistry() {
1119
+ @Override
1120
+ public void registerDataLoaders(
1121
+ DataLoaderRegistry registry,
1122
+ graphql.GraphQLContext context) {
1123
+
1124
+ DataLoaderOptions options = DataLoaderOptions.newOptions()
1125
+ .setCachingEnabled(true)
1126
+ .setBatchingEnabled(true)
1127
+ .setMaxBatchSize(100);
1128
+
1129
+ registry.register(INVENTORY_LOADER,
1130
+ DataLoader.newMappedDataLoader(inventoryDataLoader, options));
1131
+ registry.register(PARTNER_LOADER,
1132
+ DataLoader.newMappedDataLoader(partnerDataLoader, options));
1133
+ registry.register(PRODUCT_LOADER,
1134
+ DataLoader.newMappedDataLoader(productDataLoader, options));
1135
+ registry.register(WAREHOUSE_LOADER,
1136
+ DataLoader.newMappedDataLoader(warehouseDataLoader, options));
1137
+ }
1138
+ };
1139
+ }
1140
+ }
1141
+ ```
1142
+
1143
+ </details>
1144
+
1145
+ ---
1146
+
1147
+ ### 15.5 商品リゾルバの実装(DataLoader 使用)
1148
+
1149
+ <details>
1150
+ <summary>コード例: ProductResolver.java</summary>
1151
+
1152
+ ```java
1153
+ package com.example.sales.infrastructure.graphql.resolver;
1154
+
1155
+ import com.example.sales.application.port.in.ProductUseCase;
1156
+ import com.example.sales.config.DataLoaderConfig;
1157
+ import com.example.sales.domain.model.inventory.Inventory;
1158
+ import com.example.sales.domain.model.product.Product;
1159
+ import com.example.sales.infrastructure.graphql.dto.*;
1160
+ import graphql.schema.DataFetchingEnvironment;
1161
+ import org.dataloader.DataLoader;
1162
+ import org.springframework.graphql.data.method.annotation.*;
1163
+ import org.springframework.stereotype.Controller;
1164
+
1165
+ import java.util.List;
1166
+ import java.util.concurrent.CompletableFuture;
1167
+
1168
+ /**
1169
+ * 商品 GraphQL リゾルバ
1170
+ */
1171
+ @Controller
1172
+ public class ProductResolver {
1173
+
1174
+ private final ProductUseCase productUseCase;
1175
+
1176
+ public ProductResolver(ProductUseCase productUseCase) {
1177
+ this.productUseCase = productUseCase;
1178
+ }
1179
+
1180
+ // === Query ===
1181
+
1182
+ @QueryMapping
1183
+ public Product product(@Argument String productCode) {
1184
+ return productUseCase.findByCode(productCode).orElse(null);
1185
+ }
1186
+
1187
+ @QueryMapping
1188
+ public ProductConnection products(
1189
+ @Argument String category,
1190
+ @Argument Integer page,
1191
+ @Argument Integer size) {
1192
+
1193
+ int pageNum = page != null ? page : 0;
1194
+ int pageSize = size != null ? size : 20;
1195
+
1196
+ List<Product> products = productUseCase.findAll(category, pageNum, pageSize);
1197
+ long totalCount = productUseCase.count(category);
1198
+
1199
+ return ProductConnection.of(products, pageNum, pageSize, totalCount);
1200
+ }
1201
+
1202
+ // === Mutation ===
1203
+
1204
+ @MutationMapping
1205
+ public Product createProduct(@Argument CreateProductInput input) {
1206
+ Product product = Product.builder()
1207
+ .productCode(input.productCode())
1208
+ .productName(input.productName())
1209
+ .category(input.category())
1210
+ .taxCategory(input.taxCategory())
1211
+ .sellingPrice(input.sellingPrice())
1212
+ .isActive(true)
1213
+ .build();
1214
+
1215
+ return productUseCase.create(product);
1216
+ }
1217
+
1218
+ @MutationMapping
1219
+ public Product updateProduct(@Argument UpdateProductInput input) {
1220
+ return productUseCase.update(input.productCode(), product -> {
1221
+ if (input.productName() != null) {
1222
+ product.setProductName(input.productName());
1223
+ }
1224
+ if (input.category() != null) {
1225
+ product.setCategory(input.category());
1226
+ }
1227
+ if (input.sellingPrice() != null) {
1228
+ product.setSellingPrice(input.sellingPrice());
1229
+ }
1230
+ if (input.isActive() != null) {
1231
+ product.setActive(input.isActive());
1232
+ }
1233
+ return product;
1234
+ });
1235
+ }
1236
+
1237
+ @MutationMapping
1238
+ public boolean deleteProduct(@Argument String productCode) {
1239
+ return productUseCase.delete(productCode);
1240
+ }
1241
+
1242
+ // === フィールドリゾルバ(DataLoader 使用)===
1243
+
1244
+ @SchemaMapping(typeName = "Product", field = "inventories")
1245
+ public CompletableFuture<List<Inventory>> inventories(
1246
+ Product product,
1247
+ DataFetchingEnvironment env) {
1248
+
1249
+ DataLoader<String, List<Inventory>> loader =
1250
+ env.getDataLoader(DataLoaderConfig.INVENTORY_LOADER);
1251
+
1252
+ return loader.load(product.getProductCode());
1253
+ }
1254
+
1255
+ @SchemaMapping(typeName = "Product", field = "classifications")
1256
+ public List<ProductClassification> classifications(Product product) {
1257
+ return productUseCase.findClassifications(product.getProductCode());
1258
+ }
1259
+ }
1260
+ ```
1261
+
1262
+ </details>
1263
+
1264
+ ---
1265
+
1266
+ ## 第16章:トランザクション API の実装
1267
+
1268
+ ### 16.1 GraphQL Subscription とは
1269
+
1270
+ GraphQL **Subscription** は、サーバーからクライアントへのリアルタイム通知を実現する仕組みです。WebSocket を使用して双方向通信を行い、データの変更をプッシュ通知します。
1271
+
1272
+ ```plantuml
1273
+ @startuml subscription_flow
1274
+
1275
+ title GraphQL Subscription フロー
1276
+
1277
+ participant "Client" as client
1278
+ participant "WebSocket" as ws
1279
+ participant "GraphQL Server" as server
1280
+ participant "EventPublisher" as publisher
1281
+ participant "OrderService" as service
1282
+ database "PostgreSQL" as db
1283
+
1284
+ == Subscription 開始 ==
1285
+ client -> ws : subscription { orderStatusChanged }
1286
+ ws -> server : WebSocket 接続確立
1287
+ server -> server : Subscription 登録
1288
+
1289
+ == イベント発生 ==
1290
+ service -> db : 受注ステータス更新
1291
+ db --> service : 更新完了
1292
+ service -> publisher : OrderStatusChangedEvent 発行
1293
+ publisher -> server : イベント受信
1294
+ server -> ws : { orderStatusChanged: {...} }
1295
+ ws -> client : リアルタイム通知
1296
+
1297
+ == 追加イベント ==
1298
+ service -> publisher : OrderStatusChangedEvent 発行
1299
+ publisher -> server : イベント受信
1300
+ server -> ws : { orderStatusChanged: {...} }
1301
+ ws -> client : リアルタイム通知
1302
+
1303
+ == 接続終了 ==
1304
+ client -> ws : 接続クローズ
1305
+ ws -> server : Subscription 解除
1306
+
1307
+ @enduml
1308
+ ```
1309
+
1310
+ ---
1311
+
1312
+ ### 16.2 イベントクラスの定義
1313
+
1314
+ <details>
1315
+ <summary>コード例: OrderStatusChangedEvent.java</summary>
1316
+
1317
+ ```java
1318
+ package com.example.sales.domain.event;
1319
+
1320
+ import com.example.sales.domain.model.order.OrderStatus;
1321
+ import java.time.LocalDateTime;
1322
+
1323
+ /**
1324
+ * 受注ステータス変更イベント
1325
+ */
1326
+ public record OrderStatusChangedEvent(
1327
+ String orderNumber,
1328
+ OrderStatus previousStatus,
1329
+ OrderStatus currentStatus,
1330
+ String changedBy,
1331
+ LocalDateTime changedAt,
1332
+ String reason
1333
+ ) {
1334
+ public static OrderStatusChangedEvent of(
1335
+ String orderNumber,
1336
+ OrderStatus previousStatus,
1337
+ OrderStatus currentStatus,
1338
+ String changedBy) {
1339
+ return new OrderStatusChangedEvent(
1340
+ orderNumber,
1341
+ previousStatus,
1342
+ currentStatus,
1343
+ changedBy,
1344
+ LocalDateTime.now(),
1345
+ null
1346
+ );
1347
+ }
1348
+ }
1349
+ ```
1350
+
1351
+ </details>
1352
+
1353
+ <details>
1354
+ <summary>コード例: InventoryChangedEvent.java</summary>
1355
+
1356
+ ```java
1357
+ package com.example.sales.domain.event;
1358
+
1359
+ import java.time.LocalDateTime;
1360
+
1361
+ /**
1362
+ * 在庫変動イベント
1363
+ */
1364
+ public record InventoryChangedEvent(
1365
+ String warehouseCode,
1366
+ String productCode,
1367
+ InventoryChangeType changeType,
1368
+ int quantity,
1369
+ int previousQuantity,
1370
+ int currentQuantity,
1371
+ LocalDateTime timestamp
1372
+ ) {
1373
+ public enum InventoryChangeType {
1374
+ RECEIPT, // 入庫
1375
+ SHIPMENT, // 出庫
1376
+ ADJUSTMENT, // 調整
1377
+ TRANSFER, // 移動
1378
+ ALLOCATION, // 引当
1379
+ RELEASE // 引当解除
1380
+ }
1381
+
1382
+ public static InventoryChangedEvent of(
1383
+ String warehouseCode,
1384
+ String productCode,
1385
+ InventoryChangeType changeType,
1386
+ int quantity,
1387
+ int previousQuantity,
1388
+ int currentQuantity) {
1389
+ return new InventoryChangedEvent(
1390
+ warehouseCode,
1391
+ productCode,
1392
+ changeType,
1393
+ quantity,
1394
+ previousQuantity,
1395
+ currentQuantity,
1396
+ LocalDateTime.now()
1397
+ );
1398
+ }
1399
+ }
1400
+ ```
1401
+
1402
+ </details>
1403
+
1404
+ ---
1405
+
1406
+ ### 16.3 イベントパブリッシャー(Reactor Sinks)
1407
+
1408
+ <details>
1409
+ <summary>コード例: GraphQLEventPublisher.java</summary>
1410
+
1411
+ ```java
1412
+ package com.example.sales.infrastructure.graphql.subscription;
1413
+
1414
+ import com.example.sales.domain.event.*;
1415
+ import org.springframework.stereotype.Component;
1416
+ import reactor.core.publisher.Flux;
1417
+ import reactor.core.publisher.Sinks;
1418
+
1419
+ /**
1420
+ * GraphQL Subscription 用イベントパブリッシャー
1421
+ */
1422
+ @Component
1423
+ public class GraphQLEventPublisher {
1424
+
1425
+ // 受注ステータス変更
1426
+ private final Sinks.Many<OrderStatusChangedEvent> orderStatusSink =
1427
+ Sinks.many().multicast().onBackpressureBuffer();
1428
+
1429
+ // 出荷進捗
1430
+ private final Sinks.Many<ShipmentProgressEvent> shipmentProgressSink =
1431
+ Sinks.many().multicast().onBackpressureBuffer();
1432
+
1433
+ // 在庫変動
1434
+ private final Sinks.Many<InventoryChangedEvent> inventoryChangedSink =
1435
+ Sinks.many().multicast().onBackpressureBuffer();
1436
+
1437
+ // 締処理進捗
1438
+ private final Sinks.Many<ClosingProgressEvent> closingProgressSink =
1439
+ Sinks.many().multicast().onBackpressureBuffer();
1440
+
1441
+ // === 発行メソッド ===
1442
+
1443
+ public void publishOrderStatusChanged(OrderStatusChangedEvent event) {
1444
+ orderStatusSink.tryEmitNext(event);
1445
+ }
1446
+
1447
+ public void publishShipmentProgress(ShipmentProgressEvent event) {
1448
+ shipmentProgressSink.tryEmitNext(event);
1449
+ }
1450
+
1451
+ public void publishInventoryChanged(InventoryChangedEvent event) {
1452
+ inventoryChangedSink.tryEmitNext(event);
1453
+ }
1454
+
1455
+ public void publishClosingProgress(ClosingProgressEvent event) {
1456
+ closingProgressSink.tryEmitNext(event);
1457
+ }
1458
+
1459
+ // === Flux 取得メソッド ===
1460
+
1461
+ public Flux<OrderStatusChangedEvent> getOrderStatusChangedFlux() {
1462
+ return orderStatusSink.asFlux();
1463
+ }
1464
+
1465
+ public Flux<OrderStatusChangedEvent> getOrderStatusChangedFlux(String orderNumber) {
1466
+ return orderStatusSink.asFlux()
1467
+ .filter(event -> orderNumber == null ||
1468
+ event.orderNumber().equals(orderNumber));
1469
+ }
1470
+
1471
+ public Flux<ShipmentProgressEvent> getShipmentProgressFlux(String shipmentNumber) {
1472
+ return shipmentProgressSink.asFlux()
1473
+ .filter(event -> shipmentNumber == null ||
1474
+ event.shipmentNumber().equals(shipmentNumber));
1475
+ }
1476
+
1477
+ public Flux<InventoryChangedEvent> getInventoryChangedFlux(
1478
+ String warehouseCode, String productCode) {
1479
+ return inventoryChangedSink.asFlux()
1480
+ .filter(event ->
1481
+ (warehouseCode == null || event.warehouseCode().equals(warehouseCode)) &&
1482
+ (productCode == null || event.productCode().equals(productCode))
1483
+ );
1484
+ }
1485
+
1486
+ public Flux<ClosingProgressEvent> getClosingProgressFlux(String closingId) {
1487
+ return closingProgressSink.asFlux()
1488
+ .filter(event -> event.closingId().equals(closingId));
1489
+ }
1490
+ }
1491
+ ```
1492
+
1493
+ </details>
1494
+
1495
+ ---
1496
+
1497
+ ### 16.4 受注リゾルバの実装(Subscription 対応)
1498
+
1499
+ <details>
1500
+ <summary>コード例: OrderResolver.java</summary>
1501
+
1502
+ ```java
1503
+ package com.example.sales.infrastructure.graphql.resolver;
1504
+
1505
+ import com.example.sales.application.port.in.OrderUseCase;
1506
+ import com.example.sales.domain.event.OrderStatusChangedEvent;
1507
+ import com.example.sales.domain.model.order.*;
1508
+ import com.example.sales.infrastructure.graphql.dto.*;
1509
+ import com.example.sales.infrastructure.graphql.subscription.GraphQLEventPublisher;
1510
+ import org.springframework.graphql.data.method.annotation.*;
1511
+ import org.springframework.stereotype.Controller;
1512
+ import reactor.core.publisher.Flux;
1513
+
1514
+ import java.util.List;
1515
+
1516
+ /**
1517
+ * 受注 GraphQL リゾルバ
1518
+ */
1519
+ @Controller
1520
+ public class OrderResolver {
1521
+
1522
+ private final OrderUseCase orderUseCase;
1523
+ private final GraphQLEventPublisher eventPublisher;
1524
+
1525
+ public OrderResolver(OrderUseCase orderUseCase,
1526
+ GraphQLEventPublisher eventPublisher) {
1527
+ this.orderUseCase = orderUseCase;
1528
+ this.eventPublisher = eventPublisher;
1529
+ }
1530
+
1531
+ // === Query ===
1532
+
1533
+ @QueryMapping
1534
+ public Order order(@Argument String orderNumber) {
1535
+ return orderUseCase.findByNumber(orderNumber).orElse(null);
1536
+ }
1537
+
1538
+ @QueryMapping
1539
+ public OrderConnection orders(
1540
+ @Argument String status,
1541
+ @Argument String partnerCode,
1542
+ @Argument Integer page,
1543
+ @Argument Integer size) {
1544
+
1545
+ int pageNum = page != null ? page : 0;
1546
+ int pageSize = size != null ? size : 20;
1547
+
1548
+ OrderStatus orderStatus = status != null ? OrderStatus.valueOf(status) : null;
1549
+ List<Order> orders = orderUseCase.findAll(orderStatus, partnerCode, pageNum, pageSize);
1550
+ long totalCount = orderUseCase.count(orderStatus, partnerCode);
1551
+
1552
+ return OrderConnection.of(orders, pageNum, pageSize, totalCount);
1553
+ }
1554
+
1555
+ // === Mutation ===
1556
+
1557
+ @MutationMapping
1558
+ public Order createOrder(@Argument CreateOrderInput input) {
1559
+ return orderUseCase.create(
1560
+ input.partnerCode(),
1561
+ input.orderDate(),
1562
+ input.deliveryDate(),
1563
+ input.warehouseCode(),
1564
+ input.salesPersonCode(),
1565
+ input.remarks(),
1566
+ input.details()
1567
+ );
1568
+ }
1569
+
1570
+ @MutationMapping
1571
+ public Order confirmOrder(@Argument String orderNumber) {
1572
+ Order order = orderUseCase.confirm(orderNumber);
1573
+
1574
+ // イベント発行
1575
+ eventPublisher.publishOrderStatusChanged(
1576
+ OrderStatusChangedEvent.of(
1577
+ orderNumber,
1578
+ OrderStatus.DRAFT,
1579
+ OrderStatus.CONFIRMED,
1580
+ "system"
1581
+ )
1582
+ );
1583
+
1584
+ return order;
1585
+ }
1586
+
1587
+ @MutationMapping
1588
+ public Order cancelOrder(@Argument String orderNumber, @Argument String reason) {
1589
+ Order order = orderUseCase.cancel(orderNumber, reason);
1590
+
1591
+ // イベント発行
1592
+ eventPublisher.publishOrderStatusChanged(
1593
+ OrderStatusChangedEvent.withReason(
1594
+ orderNumber,
1595
+ order.getStatus(),
1596
+ OrderStatus.CANCELLED,
1597
+ "system",
1598
+ reason
1599
+ )
1600
+ );
1601
+
1602
+ return order;
1603
+ }
1604
+
1605
+ // === Subscription ===
1606
+
1607
+ @SubscriptionMapping
1608
+ public Flux<OrderStatusChangedEvent> orderStatusChanged(
1609
+ @Argument String orderNumber) {
1610
+ return eventPublisher.getOrderStatusChangedFlux(orderNumber);
1611
+ }
1612
+ }
1613
+ ```
1614
+
1615
+ </details>
1616
+
1617
+ ---
1618
+
1619
+ ### 16.5 GraphiQL によるトランザクション操作
1620
+
1621
+ <details>
1622
+ <summary>コード例: GraphQL クエリ/ミューテーション/サブスクリプション</summary>
1623
+
1624
+ ```graphql
1625
+ # 受注登録
1626
+ mutation CreateOrder {
1627
+ createOrder(input: {
1628
+ partnerCode: "CUS001"
1629
+ orderDate: "2025-12-29"
1630
+ deliveryDate: "2026-01-05"
1631
+ warehouseCode: "WH001"
1632
+ details: [
1633
+ { productCode: "PRD001", quantity: 10, unitPrice: 1000 }
1634
+ { productCode: "PRD002", quantity: 5, unitPrice: 2000 }
1635
+ ]
1636
+ }) {
1637
+ orderNumber
1638
+ status
1639
+ totalAmount
1640
+ details {
1641
+ productCode
1642
+ quantity
1643
+ amount
1644
+ }
1645
+ }
1646
+ }
1647
+
1648
+ # 受注確定
1649
+ mutation ConfirmOrder {
1650
+ confirmOrder(orderNumber: "ORD20251229001") {
1651
+ orderNumber
1652
+ status
1653
+ partner {
1654
+ partnerName
1655
+ }
1656
+ }
1657
+ }
1658
+
1659
+ # 受注ステータス監視(Subscription)
1660
+ subscription WatchOrderStatus {
1661
+ orderStatusChanged(orderNumber: "ORD20251229001") {
1662
+ orderNumber
1663
+ previousStatus
1664
+ currentStatus
1665
+ changedAt
1666
+ changedBy
1667
+ reason
1668
+ }
1669
+ }
1670
+
1671
+ # 在庫変動監視
1672
+ subscription WatchInventory {
1673
+ inventoryChanged(warehouseCode: "WH001") {
1674
+ warehouseCode
1675
+ productCode
1676
+ changeType
1677
+ quantity
1678
+ previousQuantity
1679
+ currentQuantity
1680
+ timestamp
1681
+ }
1682
+ }
1683
+ ```
1684
+
1685
+ </details>
1686
+
1687
+ ---
1688
+
1689
+ ## 第17章:エラーハンドリングとベストプラクティス
1690
+
1691
+ ### 17.1 GraphQL エラーハンドリング
1692
+
1693
+ GraphQL のエラーレスポンスは標準化された構造を持ちます:
1694
+
1695
+ <details>
1696
+ <summary>コード例: エラーレスポンス構造</summary>
1697
+
1698
+ ```json
1699
+ {
1700
+ "errors": [
1701
+ {
1702
+ "message": "商品コードが重複しています",
1703
+ "locations": [{ "line": 2, "column": 3 }],
1704
+ "path": ["createProduct"],
1705
+ "extensions": {
1706
+ "classification": "VALIDATION_ERROR",
1707
+ "code": "PRODUCT_CODE_DUPLICATE",
1708
+ "field": "productCode"
1709
+ }
1710
+ }
1711
+ ],
1712
+ "data": null
1713
+ }
1714
+ ```
1715
+
1716
+ </details>
1717
+
1718
+ #### カスタム例外クラス
1719
+
1720
+ <details>
1721
+ <summary>コード例: GraphQLErrorCode.java</summary>
1722
+
1723
+ ```java
1724
+ package com.example.sales.application.exception;
1725
+
1726
+ public enum GraphQLErrorCode {
1727
+ // バリデーションエラー
1728
+ VALIDATION_ERROR("VALIDATION_ERROR"),
1729
+ REQUIRED_FIELD_MISSING("REQUIRED_FIELD_MISSING"),
1730
+ INVALID_FORMAT("INVALID_FORMAT"),
1731
+ VALUE_OUT_OF_RANGE("VALUE_OUT_OF_RANGE"),
1732
+ DUPLICATE_VALUE("DUPLICATE_VALUE"),
1733
+
1734
+ // ビジネスロジックエラー
1735
+ BUSINESS_RULE_VIOLATION("BUSINESS_RULE_VIOLATION"),
1736
+ INSUFFICIENT_STOCK("INSUFFICIENT_STOCK"),
1737
+ INVALID_STATUS_TRANSITION("INVALID_STATUS_TRANSITION"),
1738
+ CREDIT_LIMIT_EXCEEDED("CREDIT_LIMIT_EXCEEDED"),
1739
+
1740
+ // リソースエラー
1741
+ NOT_FOUND("NOT_FOUND"),
1742
+ ALREADY_EXISTS("ALREADY_EXISTS"),
1743
+ CONFLICT("CONFLICT"),
1744
+
1745
+ // 認証・認可エラー
1746
+ UNAUTHORIZED("UNAUTHORIZED"),
1747
+ FORBIDDEN("FORBIDDEN"),
1748
+
1749
+ // システムエラー
1750
+ INTERNAL_ERROR("INTERNAL_ERROR"),
1751
+ SERVICE_UNAVAILABLE("SERVICE_UNAVAILABLE");
1752
+
1753
+ private final String code;
1754
+
1755
+ GraphQLErrorCode(String code) {
1756
+ this.code = code;
1757
+ }
1758
+
1759
+ public String getCode() {
1760
+ return code;
1761
+ }
1762
+ }
1763
+ ```
1764
+
1765
+ </details>
1766
+
1767
+ <details>
1768
+ <summary>コード例: GraphQLBusinessException.java</summary>
1769
+
1770
+ ```java
1771
+ package com.example.sales.application.exception;
1772
+
1773
+ import graphql.ErrorClassification;
1774
+ import graphql.GraphQLError;
1775
+ import graphql.language.SourceLocation;
1776
+
1777
+ import java.util.HashMap;
1778
+ import java.util.List;
1779
+ import java.util.Map;
1780
+
1781
+ public class GraphQLBusinessException extends RuntimeException implements GraphQLError {
1782
+
1783
+ private final GraphQLErrorCode errorCode;
1784
+ private final String field;
1785
+ private final Map<String, Object> additionalData;
1786
+
1787
+ public GraphQLBusinessException(String message, GraphQLErrorCode errorCode) {
1788
+ this(message, errorCode, null, null);
1789
+ }
1790
+
1791
+ public GraphQLBusinessException(String message, GraphQLErrorCode errorCode, String field) {
1792
+ this(message, errorCode, field, null);
1793
+ }
1794
+
1795
+ public GraphQLBusinessException(
1796
+ String message,
1797
+ GraphQLErrorCode errorCode,
1798
+ String field,
1799
+ Map<String, Object> additionalData) {
1800
+ super(message);
1801
+ this.errorCode = errorCode;
1802
+ this.field = field;
1803
+ this.additionalData = additionalData != null ? additionalData : new HashMap<>();
1804
+ }
1805
+
1806
+ @Override
1807
+ public List<SourceLocation> getLocations() {
1808
+ return null;
1809
+ }
1810
+
1811
+ @Override
1812
+ public ErrorClassification getErrorType() {
1813
+ return CustomErrorClassification.fromCode(errorCode);
1814
+ }
1815
+
1816
+ @Override
1817
+ public Map<String, Object> getExtensions() {
1818
+ Map<String, Object> extensions = new HashMap<>();
1819
+ extensions.put("code", errorCode.getCode());
1820
+ extensions.put("classification", getErrorType().toString());
1821
+ if (field != null) {
1822
+ extensions.put("field", field);
1823
+ }
1824
+ extensions.putAll(additionalData);
1825
+ return extensions;
1826
+ }
1827
+ }
1828
+ ```
1829
+
1830
+ </details>
1831
+
1832
+ ---
1833
+
1834
+ ### 17.2 例外リゾルバ
1835
+
1836
+ <details>
1837
+ <summary>コード例: GraphQLExceptionResolver.java</summary>
1838
+
1839
+ ```java
1840
+ package com.example.sales.infrastructure.graphql.exception;
1841
+
1842
+ import com.example.sales.application.exception.GraphQLBusinessException;
1843
+ import com.example.sales.application.exception.GraphQLErrorCode;
1844
+ import graphql.GraphQLError;
1845
+ import graphql.schema.DataFetchingEnvironment;
1846
+ import org.springframework.graphql.execution.DataFetcherExceptionResolverAdapter;
1847
+ import org.springframework.graphql.execution.ErrorType;
1848
+ import org.springframework.stereotype.Component;
1849
+
1850
+ @Component
1851
+ public class GraphQLExceptionResolver extends DataFetcherExceptionResolverAdapter {
1852
+
1853
+ @Override
1854
+ protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) {
1855
+ // カスタムビジネス例外
1856
+ if (ex instanceof GraphQLBusinessException businessEx) {
1857
+ return businessEx;
1858
+ }
1859
+
1860
+ // ドメイン例外をラップ
1861
+ if (ex instanceof IllegalArgumentException) {
1862
+ return new GraphQLBusinessException(
1863
+ ex.getMessage(),
1864
+ GraphQLErrorCode.VALIDATION_ERROR
1865
+ );
1866
+ }
1867
+
1868
+ if (ex instanceof IllegalStateException) {
1869
+ return new GraphQLBusinessException(
1870
+ ex.getMessage(),
1871
+ GraphQLErrorCode.BUSINESS_RULE_VIOLATION
1872
+ );
1873
+ }
1874
+
1875
+ // Jakarta Validation 例外
1876
+ if (ex instanceof jakarta.validation.ConstraintViolationException cve) {
1877
+ var firstViolation = cve.getConstraintViolations().iterator().next();
1878
+ return new GraphQLBusinessException(
1879
+ firstViolation.getMessage(),
1880
+ GraphQLErrorCode.VALIDATION_ERROR,
1881
+ firstViolation.getPropertyPath().toString()
1882
+ );
1883
+ }
1884
+
1885
+ // 未知の例外はログ出力して汎用メッセージを返す
1886
+ logger.error("Unexpected error in GraphQL resolver", ex);
1887
+ return GraphQLError.newError()
1888
+ .message("システムエラーが発生しました")
1889
+ .errorType(ErrorType.INTERNAL_ERROR)
1890
+ .build();
1891
+ }
1892
+ }
1893
+ ```
1894
+
1895
+ </details>
1896
+
1897
+ ---
1898
+
1899
+ ### 17.3 入力バリデーション
1900
+
1901
+ #### GraphQL ディレクティブによるバリデーション
1902
+
1903
+ <details>
1904
+ <summary>コード例: directives.graphqls</summary>
1905
+
1906
+ ```graphql
1907
+ # schema/directives.graphqls
1908
+ directive @NotBlank(message: String = "必須項目です") on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
1909
+ directive @Size(min: Int = 0, max: Int = 255, message: String) on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
1910
+ directive @Min(value: Int!, message: String) on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
1911
+ directive @Pattern(regexp: String!, message: String) on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
1912
+ directive @Email(message: String = "有効なメールアドレスを入力してください") on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
1913
+
1914
+ # 使用例
1915
+ input CreateProductInput {
1916
+ productCode: String! @NotBlank @Size(min: 1, max: 16, message: "商品コードは16文字以内で入力してください")
1917
+ productName: String! @NotBlank @Size(max: 100)
1918
+ price: BigDecimal! @Min(value: 0, message: "価格は0以上で入力してください")
1919
+ }
1920
+
1921
+ input CreatePartnerInput {
1922
+ partnerCode: String! @NotBlank @Pattern(regexp: "^[A-Z0-9]{4,10}$", message: "取引先コードは英大文字と数字4〜10文字で入力してください")
1923
+ partnerName: String! @NotBlank @Size(max: 100)
1924
+ email: String @Email
1925
+ creditLimit: BigDecimal @Min(value: 0)
1926
+ }
1927
+ ```
1928
+
1929
+ </details>
1930
+
1931
+ #### Jakarta Validation との統合
1932
+
1933
+ <details>
1934
+ <summary>コード例: CreateProductInputDto.java</summary>
1935
+
1936
+ ```java
1937
+ package com.example.sales.application.dto;
1938
+
1939
+ import jakarta.validation.constraints.*;
1940
+ import java.math.BigDecimal;
1941
+
1942
+ public record CreateProductInputDto(
1943
+ @NotBlank(message = "商品コードは必須です")
1944
+ @Size(max = 16, message = "商品コードは16文字以内で入力してください")
1945
+ @Pattern(regexp = "^[A-Z0-9]+$", message = "商品コードは英大文字と数字のみ使用可能です")
1946
+ String productCode,
1947
+
1948
+ @NotBlank(message = "商品名は必須です")
1949
+ @Size(max = 100, message = "商品名は100文字以内で入力してください")
1950
+ String productName,
1951
+
1952
+ @NotNull(message = "価格は必須です")
1953
+ @DecimalMin(value = "0", message = "価格は0以上で入力してください")
1954
+ @Digits(integer = 10, fraction = 2, message = "価格の形式が正しくありません")
1955
+ BigDecimal price,
1956
+
1957
+ @Min(value = 0, message = "在庫数は0以上で入力してください")
1958
+ Integer stockQuantity,
1959
+
1960
+ @Size(max = 500, message = "備考は500文字以内で入力してください")
1961
+ String notes
1962
+ ) {}
1963
+ ```
1964
+
1965
+ </details>
1966
+
1967
+ ---
1968
+
1969
+ ### 17.4 セキュリティ
1970
+
1971
+ #### 認可ディレクティブ
1972
+
1973
+ <details>
1974
+ <summary>コード例: 認可ディレクティブ</summary>
1975
+
1976
+ ```graphql
1977
+ # スキーマレベルでの認可定義
1978
+ directive @auth(
1979
+ roles: [String!]!
1980
+ ) on FIELD_DEFINITION
1981
+
1982
+ type Mutation {
1983
+ # 管理者のみ
1984
+ deleteProduct(productCode: ID!): Boolean! @auth(roles: ["ADMIN"])
1985
+
1986
+ # 営業担当と管理者
1987
+ createOrder(input: CreateOrderInput!): Order! @auth(roles: ["SALES", "ADMIN"])
1988
+
1989
+ # 経理担当と管理者
1990
+ executeClosing(input: ExecuteClosingInput!): ClosingResult! @auth(roles: ["ACCOUNTING", "ADMIN"])
1991
+ }
1992
+ ```
1993
+
1994
+ </details>
1995
+
1996
+ #### クエリ深度制限
1997
+
1998
+ <details>
1999
+ <summary>コード例: クエリ深度制限</summary>
2000
+
2001
+ ```java
2002
+ @Bean
2003
+ public Instrumentation maxQueryDepthInstrumentation() {
2004
+ return new MaxQueryDepthInstrumentation(10);
2005
+ }
2006
+
2007
+ @Bean
2008
+ public Instrumentation maxQueryComplexityInstrumentation() {
2009
+ return new MaxQueryComplexityInstrumentation(100);
2010
+ }
2011
+ ```
2012
+
2013
+ </details>
2014
+
2015
+ ---
2016
+
2017
+ ### 17.5 運用のベストプラクティス
2018
+
2019
+ #### ログインターセプター
2020
+
2021
+ <details>
2022
+ <summary>コード例: GraphQLLoggingInterceptor.java</summary>
2023
+
2024
+ ```java
2025
+ @Component
2026
+ public class GraphQLLoggingInterceptor implements WebGraphQlInterceptor {
2027
+
2028
+ private static final Logger logger = LoggerFactory.getLogger(GraphQLLoggingInterceptor.class);
2029
+
2030
+ @Override
2031
+ public Mono<WebGraphQlResponse> intercept(WebGraphQlRequest request, Chain chain) {
2032
+ String requestId = UUID.randomUUID().toString().substring(0, 8);
2033
+ String operationName = request.getOperationName();
2034
+ Instant start = Instant.now();
2035
+
2036
+ MDC.put("requestId", requestId);
2037
+ MDC.put("operationName", operationName);
2038
+
2039
+ logger.info("GraphQL リクエスト開始: operation={}", operationName);
2040
+
2041
+ return chain.next(request)
2042
+ .doOnNext(response -> {
2043
+ Duration duration = Duration.between(start, Instant.now());
2044
+
2045
+ if (response.getErrors().isEmpty()) {
2046
+ logger.info("GraphQL リクエスト完了: operation={}, duration={}ms",
2047
+ operationName, duration.toMillis());
2048
+ } else {
2049
+ logger.warn("GraphQL リクエスト完了(エラーあり): operation={}, duration={}ms, errors={}",
2050
+ operationName, duration.toMillis(), response.getErrors().size());
2051
+ }
2052
+ })
2053
+ .doFinally(signalType -> {
2054
+ MDC.remove("requestId");
2055
+ MDC.remove("operationName");
2056
+ });
2057
+ }
2058
+ }
2059
+ ```
2060
+
2061
+ </details>
2062
+
2063
+ #### メトリクス収集
2064
+
2065
+ <details>
2066
+ <summary>コード例: GraphQLMetricsCollector.java</summary>
2067
+
2068
+ ```java
2069
+ @Component
2070
+ public class GraphQLMetricsCollector implements WebGraphQlInterceptor {
2071
+
2072
+ private final Timer queryTimer;
2073
+ private final Timer mutationTimer;
2074
+ private final Counter errorCounter;
2075
+ private final Counter successCounter;
2076
+
2077
+ public GraphQLMetricsCollector(MeterRegistry registry) {
2078
+ this.queryTimer = Timer.builder("graphql.query.duration")
2079
+ .description("GraphQL クエリ実行時間")
2080
+ .register(registry);
2081
+
2082
+ this.mutationTimer = Timer.builder("graphql.mutation.duration")
2083
+ .description("GraphQL ミューテーション実行時間")
2084
+ .register(registry);
2085
+
2086
+ this.errorCounter = Counter.builder("graphql.errors")
2087
+ .description("GraphQL エラー数")
2088
+ .register(registry);
2089
+
2090
+ this.successCounter = Counter.builder("graphql.success")
2091
+ .description("GraphQL 成功数")
2092
+ .register(registry);
2093
+ }
2094
+
2095
+ @Override
2096
+ public Mono<WebGraphQlResponse> intercept(WebGraphQlRequest request, Chain chain) {
2097
+ Timer timer = request.getDocument().contains("mutation")
2098
+ ? mutationTimer
2099
+ : queryTimer;
2100
+
2101
+ return Mono.fromSupplier(timer::start)
2102
+ .flatMap(sample -> chain.next(request)
2103
+ .doOnNext(response -> {
2104
+ sample.stop(timer);
2105
+
2106
+ if (response.getErrors().isEmpty()) {
2107
+ successCounter.increment();
2108
+ } else {
2109
+ errorCounter.increment(response.getErrors().size());
2110
+ }
2111
+ })
2112
+ );
2113
+ }
2114
+ }
2115
+ ```
2116
+
2117
+ </details>
2118
+
2119
+ ---
2120
+
2121
+ ## Part 10-E のまとめ
2122
+
2123
+ ### 実装した機能一覧
2124
+
2125
+ | 章 | 内容 | 主要技術 |
2126
+ |---|---|---|
2127
+ | **第14章: 基礎** | GraphQL サーバーの基礎 | Spring for GraphQL, スキーマ駆動開発 |
2128
+ | **第15章: マスタ API** | N+1 問題対策、ページネーション | DataLoader, Connection パターン |
2129
+ | **第16章: トランザクション API** | リアルタイム通知、非同期処理 | Subscription, Reactor Sinks |
2130
+ | **第17章: エラーハンドリング** | バリデーション、セキュリティ | ディレクティブ, Jakarta Validation |
2131
+
2132
+ ### 実装した GraphQL 操作
2133
+
2134
+ - **Query**: 商品・取引先・倉庫・受注・出荷・請求の取得
2135
+ - **Mutation**: CRUD 操作、受注確定、出荷確定、締処理
2136
+ - **Subscription**: 受注ステータス変更、出荷進捗、在庫変動、締処理進捗
2137
+
2138
+ ### アーキテクチャの特徴
2139
+
2140
+ ```plantuml
2141
+ @startuml
2142
+
2143
+ package "Adapter Layer (in)" {
2144
+ [GraphQL Resolver] as resolver
2145
+ [Exception Resolver] as exception_resolver
2146
+ [Validation Directive] as validation
2147
+ [DataLoader Registry] as dataloader
2148
+ [Logging Interceptor] as logging
2149
+ [Metrics Collector] as metrics
2150
+ }
2151
+
2152
+ package "Application Layer" {
2153
+ [UseCase] as usecase
2154
+ [DTO] as dto
2155
+ [Exception] as app_exception
2156
+ }
2157
+
2158
+ package "Domain Layer" {
2159
+ [Domain Model] as domain
2160
+ [Domain Service] as domain_service
2161
+ [Repository Interface] as repo_interface
2162
+ }
2163
+
2164
+ package "Adapter Layer (out)" {
2165
+ [Repository Implementation] as repo_impl
2166
+ [MyBatis Mapper] as mapper
2167
+ }
2168
+
2169
+ database "PostgreSQL" as db
2170
+
2171
+ ' Interceptor チェーン
2172
+ logging --> metrics
2173
+ metrics --> resolver
2174
+
2175
+ ' バリデーション
2176
+ validation --> resolver
2177
+
2178
+ ' メイン処理フロー
2179
+ resolver --> usecase
2180
+ resolver --> dataloader
2181
+ usecase --> domain_service
2182
+ usecase --> repo_interface
2183
+ domain_service --> domain
2184
+ repo_interface <|.. repo_impl
2185
+ repo_impl --> mapper
2186
+ mapper --> db
2187
+
2188
+ ' 例外処理
2189
+ resolver ..> exception_resolver : throws
2190
+ usecase ..> app_exception : throws
2191
+
2192
+ ' DataLoader
2193
+ dataloader --> repo_interface
2194
+
2195
+ @enduml
2196
+ ```
2197
+
2198
+ ### 技術スタック
2199
+
2200
+ | カテゴリ | 技術 |
2201
+ |---------|------|
2202
+ | **言語** | Java 21 |
2203
+ | **フレームワーク** | Spring Boot 4.0, Spring for GraphQL |
2204
+ | **リアルタイム** | WebSocket, Reactor (Sinks) |
2205
+ | **ORM** | MyBatis 3.0 |
2206
+ | **データベース** | PostgreSQL 16 |
2207
+ | **テスト** | JUnit 5, spring-graphql-test, TestContainers |
2208
+
2209
+ ### API 形式の比較と選択基準
2210
+
2211
+ | 観点 | REST API | gRPC | GraphQL |
2212
+ |------|----------|------|---------|
2213
+ | **データ取得** | 固定レスポンス | 固定レスポンス | クライアント指定 |
2214
+ | **エンドポイント** | 複数 | 複数 | 単一 |
2215
+ | **Over-fetching** | 発生しやすい | 発生しやすい | 防止可能 |
2216
+ | **Under-fetching** | 発生しやすい | 発生しやすい | 防止可能 |
2217
+ | **リアルタイム** | WebSocket 別実装 | ストリーミング | Subscription |
2218
+ | **N+1 問題** | 発生しにくい | 発生しにくい | DataLoader で解決 |
2219
+ | **主な用途** | 汎用 API | マイクロサービス | フロントエンド向け |
2220
+
2221
+ ### GraphQL を選択する場面
2222
+
2223
+ 1. **複雑なデータ構造**: 関連データを柔軟に取得したい
2224
+ 2. **フロントエンド主導**: クライアントが必要なデータを指定したい
2225
+ 3. **Over-fetching 回避**: 帯域幅の節約が重要
2226
+ 4. **リアルタイム通知**: Subscription による統一的な通知機構が必要
2227
+ 5. **API 統合**: 複数のバックエンドを単一 API で公開したい
2228
+
2229
+ GraphQL は REST API と比較して、クライアントが必要なデータを柔軟に取得できる点が大きな利点です。特に複雑なデータ構造を持つ販売管理システムでは、DataLoader と Subscription を活用することで、効率的かつリアルタイムな API を提供できます。