JK
Projets
JK
>CHARGEMENT // CHARGEMENT
INITIALISATION DE LA VUE
Conçu et développé parJK
JK
>CHARGEMENT // PROJECT DETAILS
PARSING ARCHITECTURE, DIAGRAMS & API ENDPOINTS
Retour aux projets
Voir sur GitHub
Backend de Microservices
Terminénestjspostgrestypescriptjesteslintdockergithubactionspostmanswagger

Backend de Microservices

Architecture moderne de microservices avec NestJS, PostgreSQL et Docker orchestrée par une passerelle API Gateway centralisée.

Problème et solution

Séparation nette des responsabilités entre le routage (API Gateway), la logique métier (services autonomes) et la persistance des données pour un déploiement indépendant.

Fonctionnalités

  • Services découplés pour les Produits et les Commandes
  • API Gateway pour le routage centralisé et la sécurité
  • Base de données PostgreSQL orchestrée avec Docker Compose
  • Structure monorepo gérée par TurboRepo
  • Pipeline CI/CD GitHub Actions avec déploiement automatique sur Docker Hub
  • Suite complète de tests unitaires avec Jest

Stack technique

TechnologieVersionObjectifPourquoi ce choix
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

Architecture

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

Structure du projet

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

Points d'API

API Gateway (port 3000)

MéthodeRouteObjectif
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 (port 3001)

MéthodeRouteObjectif
POST/productsCreate product
GET/productsList all products
GET/products/:idGet product by ID
PATCH/products/:idUpdate product
DELETE/products/:idDelete product

Orders Service (port 3002)

MéthodeRouteObjectif
POST/ordersCreate order
GET/ordersList all orders
GET/orders/:idGet order by ID

Conception de la base de données

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

ColonneTypeNotes
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

ColonneTypeNotes
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.

Décisions de conception clés

Shared PostgreSQL Database

Décision : Both services connect to the same PostgreSQL instance and database (procura_db)

Pourquoi : Simplifies development and deployment — one database to manage

Avantages : Simpler infrastructure, lower resource usage, easier local development

Compromis : Violates database-per-service principle, creates hidden coupling, makes independent scaling harder

JSONB for Order Products

Décision : Order entity stores product data as JSONB rather than foreign key references

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

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

Compromis : No referential integrity, data duplication, no automatic product validation on order creation

API Key Authentication

Décision : Simple static API key in x-api-key header, compared against environment variable

Pourquoi : Simplest possible authentication for demonstration purposes

Avantages : Minimal implementation, no token management, no state

Compromis : No user identity, no fine-grained permissions, key is static and shared

HTTP-based Inter-service Communication

Décision : API Gateway communicates with downstream services via synchronous HTTP (Axios)

Pourquoi : Simplest approach for synchronous request-response pattern

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

Compromis : Synchronous coupling, no retry/circuit breaker, no async processing

Multi-stage Docker Builds

Décision : Each service uses a 3-stage Dockerfile (deps → builder → runner)

Pourquoi : Minimizes final image size and attack surface

Avantages : Production images contain only runtime dependencies and compiled code

Compromis : Build time for each stage, no layer caching optimization for src changes

TypeORM synchronize: true

Décision : Both services use synchronize: true in TypeORM config

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

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

Compromis : Dangerous in production — can cause data loss on schema changes

Tests

Jest ^30.0.0 with ts-jest ^29.2.5•34 tests unitaires

Ce qui est testé

  • 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)

Couverture manquante

  • 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)

Défis clés

  • Coordonner plusieurs services tout en garantissant l'isolation des pannes
  • Configurer des pipelines CI/CD fiables pour plusieurs images Docker

Apprentissages clés

  • Modèles d'API Gateway pour centraliser les requêtes entrantes
  • Mise en réseau de conteneurs et orchestration Docker Compose