Skip to content

mvrcoag/nodejs-express-hexagonal-architecture

Repository files navigation

Hexagonal Node + Express API

Small Node.js + TypeScript project that demonstrates hexagonal architecture with a Postgres-backed User module. It exposes a simple CRUD API for users and keeps domain logic isolated from infrastructure.

Tech stack

  • Node.js, Express
  • TypeScript, ts-node
  • Postgres (pg)
  • Jest, Supertest

Project structure

  • src/main.ts: Express app bootstrap
  • src/lib/Shared: cross-cutting concerns (env, service container)
  • src/lib/User/domain: entities and value objects
  • src/lib/User/application: use cases
  • src/lib/User/infrastructure: Express controller/router + Postgres repository

Requirements

  • Node.js
  • Postgres database

Configuration

Create a .env file at the project root:

DATABASE_URL=postgres://user:password@localhost:5432/hexagonal

The app expects a users table with a created_at default because inserts do not set it explicitly:

CREATE TABLE users (
  id uuid PRIMARY KEY,
  name text NOT NULL,
  email text NOT NULL,
  created_at timestamp NOT NULL DEFAULT now()
);

Install

npm install

Run

npm run dev

The server listens on http://localhost:3000.

Build and start

npm run build
npm start

Tests

npm test

Note: integration tests for PostgresUserRepository require DATABASE_URL and a running database.

API

All endpoints accept and return JSON.

GET /users

Returns an array of users.

GET /users/:id

Returns a single user or 404 if not found.

POST /users

Creates a user. Body:

{
  "id": "9b9b4be2-8e6c-4a01-9f84-ff1cf7b2f7a2",
  "name": "Ada",
  "email": "ada@example.com",
  "createdAt": "2024-01-01T10:00:00.000Z"
}

PUT /users

Updates a user. Body is the same as create. Returns 204 or 404 if not found.

DELETE /users/:id

Deletes a user. Returns 204 or 404 if not found.

Domain validation rules

  • id must be at least 5 characters
  • name must be at least 3 characters
  • email must contain @ and .
  • createdAt must be in the past

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors