JK
Projekt
JK
>LADDAR // LADDAR
INITIERAR VY
Byggd och designad avJK
JK
>LADDAR // PROJECT DETAILS
PARSING ARCHITECTURE, DIAGRAMS & API ENDPOINTS
Tillbaka till projekt
Visa på GitHub
Mikrotjänst-backend
Slutförtnestjspostgrestypescriptjesteslintdockergithubactionspostmanswagger

Mikrotjänst-backend

Produktionsredo mikrotjänstarkitektur med NestJS, PostgreSQL och Docker samordnad via en central API Gateway.

Problem och lösning

Uppdelning av routing (API Gateway), domänlogik (oberoende tjänster) och databas för fristående driftsättning och skalning.

Funktioner

  • Fristående mikrotjänster för Produkter och Beställningar
  • API Gateway för centraliserad dirigering och säkerhet
  • PostgreSQL-databas orkestrerad med Docker Compose
  • Monorepo-struktur hanterad med TurboRepo
  • Automatiserad driftsättning till Docker Hub via GitHub Actions CI/CD
  • Omfattande enhetstester med Jest

Teknikstack

TeknikVersionSyfteVarför vald
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

Arkitektur

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

Projektstruktur

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

API-slutpunkter

API Gateway (port 3000)

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

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

MetodRuttSyfte
POST/ordersCreate order
GET/ordersList all orders
GET/orders/:idGet order by ID

Databasdesign

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

KolumnTypAnteckningar
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

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

Viktiga designbeslut

Shared PostgreSQL Database

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

Varför: Simplifies development and deployment — one database to manage

Fördelar: Simpler infrastructure, lower resource usage, easier local development

Avvägningar: Violates database-per-service principle, creates hidden coupling, makes independent scaling harder

JSONB for Order Products

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

Varför: Decouples order data from product lifecycle — orders are immutable snapshots

Fördelar: Orders are self-contained, product changes don't affect historical orders

Avvägningar: No referential integrity, data duplication, no automatic product validation on order creation

API Key Authentication

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

Varför: Simplest possible authentication for demonstration purposes

Fördelar: Minimal implementation, no token management, no state

Avvägningar: No user identity, no fine-grained permissions, key is static and shared

HTTP-based Inter-service Communication

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

Varför: Simplest approach for synchronous request-response pattern

Fördelar: Easy to understand, debug, and test; standard HTTP tooling

Avvägningar: Synchronous coupling, no retry/circuit breaker, no async processing

Multi-stage Docker Builds

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

Varför: Minimizes final image size and attack surface

Fördelar: Production images contain only runtime dependencies and compiled code

Avvägningar: Build time for each stage, no layer caching optimization for src changes

TypeORM synchronize: true

Beslut: Both services use synchronize: true in TypeORM config

Varför: Auto-creates/updates database schema from entities during development

Fördelar: No migration files needed, schema stays in sync with code

Avvägningar: Dangerous in production — can cause data loss on schema changes

Tester

Jest ^30.0.0 with ts-jest ^29.2.5•34 enhetstester

Vad som testas

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

Saknad täckning

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

Viktiga utmaningar

  • Coordinating multiple services while ensuring fault isolation
  • Setting up CI/CD pipelines for multi-image Docker builds
  • Managing environment variables cleanly inside Docker

Viktiga lärdomar

  • Effective use of API Gateway pattern
  • Advanced Docker container orchestration with dependencies
  • Dependency isolation using monorepo tooling (TurboRepo)