JK
プロジェクト
JK
>読み込み中 // 読み込み中
ビューを初期化中
制作・デザイン:JK
JK
>読み込み中 // PROJECT DETAILS
PARSING ARCHITECTURE, DIAGRAMS & API ENDPOINTS
プロジェクト一覧に戻る
GitHubで見る
マイクロサービス・バックエンド
完了nestjspostgrestypescriptjesteslintdockergithubactionspostmanswagger

マイクロサービス・バックエンド

NestJS、PostgreSQL、Dockerを用い、API Gateway経由で商品・注文サービスを統括する実用的なマイクロサービス構成。

課題と解決策

ルーティング(Gateway)、ドメインロジック(各サービス)、データ永続化(DB)の関心事を分離し、サービスごとの独立デプロイと水平スケーリングを可能にします。

機能

  • 商品・注文を分離した疎結合マイクロサービス構成
  • 一元ルーティングと認証を行うAPI Gateway
  • Docker ComposeによるPostgreSQLコンテナ統合
  • TurboRepoを活用したモノレポ構造
  • GitHub ActionsによるDocker Hubへの自動ビルド・デプロイCI/CD
  • Jestによるユニットテストの網羅

技術スタック

技術バージョン目的採用理由
TypeScript^5.7.3Primary language for all servicesType safety, NestJS ecosystem standard
NestJS^11.0.1Application frameworkModular architecture, dependency injection, TypeScript-first
TypeORM^0.3.27ORM for PostgreSQL accessActive Record/Repository pattern, NestJS integration
PostgreSQL15Primary databaseJSONB support, ACID compliance, reliability
Docker—Containerization for all servicesConsistent environments, reproducible deployments
Turborepo^2.5.8Monorepo task orchestrationFast parallel builds, caching, npm workspaces integration
GitHub Actions—CI/CD pipeline executionFree for public repos, tight Git integration
Jest^30.0.0Unit testing frameworkNestJS default, snapshot support
Swagger^11.2.0API documentationAuto-generates OpenAPI from decorators

アーキテクチャ

Client

API Gateway

:3000

Products Service

:3001

Orders Service

:3002

PostgreSQL

:5432
Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

Core System Components

  • API Gateway for routing requests to internal services
  • Products & Orders service as independent NestJS services
  • Docker Compose orchestration
  • PostgreSQL container

Infrastructure

  • GitHub Actions CI (lint, test, build)
  • Docker Hub CD image deployment
  • Environment variable management

プロジェクト構成

.github
workflows
apps
api-gateway
orders-service
products-service
libs
common
docker-compose.ymlOrchestrates all services and PostgreSQL database

APIエンドポイント

API Gateway (ポート 3000)

メソッドルート目的
GET/productsList all products
GET/products/:idGet product by ID
POST/productsCreate product
PATCH/products/:idUpdate product
DELETE/products/:idDelete product
GET/ordersList all orders
GET/orders/:idGet order by ID
POST/ordersCreate order

Products Service (ポート 3001)

メソッドルート目的
POST/productsCreate product
GET/productsList all products
GET/products/:idGet product by ID
PATCH/products/:idUpdate product
DELETE/products/:idDelete product

Orders Service (ポート 3002)

メソッドルート目的
POST/ordersCreate order
GET/ordersList all orders
GET/orders/:idGet order by ID

データベース設計

product

6 cols
idPK
SERIAL
code
VARCHAR
name
VARCHAR
description
VARCHAR
price
DECIMAL
image
VARCHAR

order

4 cols
idPK
SERIAL
customer
JSONB
products
JSONB
totalAmount
DECIMAL
Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

product

カラム型備考
idPKSERIALAuto-generated primary key
codeVARCHARProduct SKU/code
nameVARCHARProduct display name
descriptionVARCHARProduct description
priceDECIMALProduct price
imageVARCHARImage URL

No explicit indexes beyond primary key. No unique constraints on code.

order

カラム型備考
idPKSERIALAuto-generated primary key
customerJSONBStores {name, phone}
productsJSONBArray of {id, name, rate, qty}
totalAmountDECIMALTotal order amount

Products stored as JSONB snapshot — intentional denormalization. No foreign keys to product table.

No foreign key relationships. Order.products is a JSONB snapshot — orders are self-contained records that do not reference the product table. Product price changes do not affect existing orders.

主要な設計判断

Shared PostgreSQL Database

判断: Both services connect to the same PostgreSQL instance and database (procura_db)

理由: Simplifies development and deployment — one database to manage

利点: Simpler infrastructure, lower resource usage, easier local development

トレードオフ: Violates database-per-service principle, creates hidden coupling, makes independent scaling harder

JSONB for Order Products

判断: Order entity stores product data as JSONB rather than foreign key references

理由: Decouples order data from product lifecycle — orders are immutable snapshots

利点: Orders are self-contained, product changes don't affect historical orders

トレードオフ: No referential integrity, data duplication, no automatic product validation on order creation

API Key Authentication

判断: Simple static API key in x-api-key header, compared against environment variable

理由: Simplest possible authentication for demonstration purposes

利点: Minimal implementation, no token management, no state

トレードオフ: No user identity, no fine-grained permissions, key is static and shared

HTTP-based Inter-service Communication

判断: API Gateway communicates with downstream services via synchronous HTTP (Axios)

理由: Simplest approach for synchronous request-response pattern

利点: Easy to understand, debug, and test; standard HTTP tooling

トレードオフ: Synchronous coupling, no retry/circuit breaker, no async processing

Multi-stage Docker Builds

判断: Each service uses a 3-stage Dockerfile (deps → builder → runner)

理由: Minimizes final image size and attack surface

利点: Production images contain only runtime dependencies and compiled code

トレードオフ: Build time for each stage, no layer caching optimization for src changes

TypeORM synchronize: true

判断: Both services use synchronize: true in TypeORM config

理由: Auto-creates/updates database schema from entities during development

利点: No migration files needed, schema stays in sync with code

トレードオフ: Dangerous in production — can cause data loss on schema changes

テスト

Jest ^30.0.0 with ts-jest ^29.2.5•ユニットテスト 34 件

テスト内容

  • API Gateway: root health check, all proxy operations (products + orders)
  • Products Service: controller methods (create, findAll, findOne, update, remove)
  • Products Service: service methods (create, findAll, findOne, update, remove)
  • Orders Service: controller methods (create, findAll, findOne, id conversion)
  • Orders Service: service methods (create, findAll, findOne)

不足しているカバレッジ

  • Integration tests with real database
  • API Gateway ↔ Service integration tests
  • Middleware tests for API key validation
  • Validation error scenario tests
  • Error path tests (404, 500 scenarios)

主な課題

  • 複数サービス間の障害分離と協調動作の担保
  • 複数コンテナイメージに対応したCI/CDパイプラインの構築

学んだこと

  • API Gatewayパターンによる統一エンドポイント設計
  • Dockerネットワークを用いたサービス間セキュア通信