An open API service indexing awesome lists of open source software.

https://github.com/nanotaboada/ts-node-samples-express-restful

๐Ÿงช Proof of Concept for a RESTful API made with Node.js 20 (LTS), Express.js 4 in TypeScript
https://github.com/nanotaboada/ts-node-samples-express-restful

express-js expressjs node-js nodejs proof-of-concept rest-api restful-api samples sqlite typescript

Last synced: 3 months ago
JSON representation

๐Ÿงช Proof of Concept for a RESTful API made with Node.js 20 (LTS), Express.js 4 in TypeScript

Awesome Lists containing this project

README

          

# ๐Ÿงช RESTful API with Node.js and Express.js in TypeScript

[![Node.js CI](https://github.com/nanotaboada/ts-node-samples-express-restful/actions/workflows/node-ci.yml/badge.svg)](https://github.com/nanotaboada/ts-node-samples-express-restful/actions/workflows/node-ci.yml)
[![Node.js CD](https://github.com/nanotaboada/ts-node-samples-express-restful/actions/workflows/node-cd.yml/badge.svg)](https://github.com/nanotaboada/ts-node-samples-express-restful/actions/workflows/node-cd.yml)
[![CodeQL Advanced](https://github.com/nanotaboada/ts-node-samples-express-restful/actions/workflows/codeql.yml/badge.svg)](https://github.com/nanotaboada/ts-node-samples-express-restful/actions/workflows/codeql.yml)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=nanotaboada_ts-node-samples-express-restful&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=nanotaboada_ts-node-samples-express-restful)
[![codecov](https://codecov.io/gh/nanotaboada/ts-node-samples-express-restful/branch/master/graph/badge.svg?token=VxKaWl2DfD)](https://codecov.io/gh/nanotaboada/ts-node-samples-express-restful)
[![CodeFactor](https://www.codefactor.io/repository/github/nanotaboada/ts-node-samples-express-restful/badge)](https://www.codefactor.io/repository/github/nanotaboada/ts-node-samples-express-restful)
[![License: MIT](https://img.shields.io/badge/License-MIT-3DA639.svg)](https://opensource.org/licenses/MIT)
![Dependabot](https://img.shields.io/badge/Dependabot-contributing-025E8C?logo=dependabot&logoColor=white&labelColor=181818)
![GitHub Copilot](https://img.shields.io/badge/GitHub_Copilot-contributing-8662C5?logo=githubcopilot&logoColor=white&labelColor=181818)
![Claude](https://img.shields.io/badge/Claude-Sonnet_4.6-D97757?logo=claude&logoColor=white&labelColor=181818)
![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/nanotaboada/ts-node-samples-express-restful?utm_source=oss&utm_medium=github&utm_campaign=nanotaboada%2Fts-node-samples-express-restful&labelColor=181818&link=https%3A%2F%2Fcoderabbit.ai&label=CodeRabbit+Reviews)

Proof of Concept for a RESTful API made with [Node.js](https://nodejs.org/) [LTS/Krypton (v24)](https://nodejs.org/en/blog/release/v24.11.1) and [Express.js](https://expressjs.com/) 5 in [TypeScript](https://www.typescriptlang.org/). Manage football player data with SQLite, Sequelize ORM, Swagger documentation, and in-memory caching.

## Table of Contents

- [Features](#features)
- [Tech Stack](#tech-stack)
- [Project Structure](#project-structure)
- [Architecture](#architecture)
- [Architecture Decisions](#architecture-decisions)
- [API Reference](#api-reference)
- [Prerequisites](#prerequisites)
- [Quick Start](#quick-start)
- [Testing](#testing)
- [Containers](#containers)
- [Releases](#releases)
- [Environment Variables](#environment-variables)
- [Command Summary](#command-summary)
- [Contributing](#contributing)
- [Legal](#legal)

## Features

- ๐Ÿ—๏ธ **Modern TypeScript architecture** - Native ESM, strict mode, layered architecture with interface-based contracts
- ๐Ÿ“š **Interactive API exploration** - Auto-generated OpenAPI docs with Swagger UI and `.rest` HTTP file for VS Code REST Client
- โšก **Performance optimizations** - In-memory caching with node-cache, Sequelize ORM, and efficient SQLite operations
- ๐Ÿงช **Comprehensive integration tests** - Full endpoint coverage with Jest/Supertest and automated reporting to Codecov
- ๐Ÿ“– **Token-efficient documentation** - Auto-loaded Copilot instructions for AI-assisted development
- ๐Ÿณ **Full containerization** - Multi-stage Docker builds with Docker Compose orchestration
- ๐Ÿ”„ **Complete CI/CD pipeline** - Automated linting (ESLint/Prettier), testing, Docker publishing, and GitHub releases
- โšฝ **Football-themed semantic versioning** - Memorable, alphabetical release names using football terminology

## Tech Stack

| Category | Technology |
|------------------------|------------------------------------------------------------------------------------------------------------------------------|
| **Runtime** | [Node.js 24 (LTS/Krypton)](https://github.com/nodejs/node) |
| **Language** | [TypeScript 5.9](https://github.com/microsoft/TypeScript) |
| **Module System** | Native ECMAScript Modules (ESM) - uses [tsx](https://github.com/privatenumber/tsx) for execution |
| **Framework** | [Express.js 5](https://github.com/expressjs/express) |
| **Database** | [SQLite3](https://github.com/sqlite/sqlite) with [Sequelize ORM](https://github.com/sequelize/sequelize) |
| **Caching** | [node-cache](https://github.com/node-cache/node-cache) |
| **Documentation** | [Swagger (OpenAPI 3.0)](https://github.com/swagger-api/swagger-ui) |
| **Security** | [Helmet](https://github.com/helmetjs/helmet), [CORS](https://github.com/expressjs/cors), [express-rate-limit](https://github.com/express-rate-limit/express-rate-limit) |
| **Testing** | [Jest 30](https://github.com/jestjs/jest) with [Supertest](https://github.com/ladjs/supertest) |
| **Containerization** | [Docker](https://github.com/docker) with multi-stage builds |
| **Code Quality** | [ESLint](https://github.com/eslint/eslint), [Prettier](https://github.com/prettier/prettier), [Commitlint](https://github.com/conventional-changelog/commitlint) |
| **Dev Tools** | [tsx](https://github.com/privatenumber/tsx) (TypeScript executor), [nodemon](https://github.com/remy/nodemon) |

> ๐Ÿ’ก **Note:** While the repository name references `ts-node` (the original implementation), the project now uses [tsx](https://github.com/privatenumber/tsx) for faster, cleaner TypeScript execution without experimental flags.

## Project Structure

```text
src/
โ”œโ”€โ”€ app.ts # Express app setup & middleware configuration
โ”œโ”€โ”€ server.ts # HTTP server initialization & lifecycle
โ”œโ”€โ”€ controllers/ # Request handlers with Swagger annotations
โ”œโ”€โ”€ services/ # Business logic + caching layer
โ”œโ”€โ”€ database/ # Sequelize DB access (interfaces + implementations)
โ”œโ”€โ”€ models/ # Sequelize models (Player)
โ”œโ”€โ”€ routes/ # Express Router definitions
โ”œโ”€โ”€ docs/ # Swagger configuration & doc generation
โ”œโ”€โ”€ middlewares/ # Custom middleware (rate limiter, validators, Swagger CSP)
โ””โ”€โ”€ utils/ # Pino logger configuration

rest/ # HTTP request files for VS Code REST Client
tests/ # Integration tests with supertest
scripts/ # Docker entrypoint & healthcheck scripts
storage/ # Pre-seeded SQLite database
```

## Architecture

Layered architecture with dependency injection via constructors and interface-based contracts.

```mermaid
%%{init: {
"theme": "default",
"themeVariables": {
"fontFamily": "Fira Code, Consolas, monospace",
"textColor": "#555",
"lineColor": "#555",
"lineWidth": 2,
"clusterBkg": "#f5f5f5",
"clusterBorder": "#999"
}
}}%%

graph RL

tests[tests]

subgraph Layer 1[" "]
server[server]
app[app]
end

subgraph Layer 2[" "]
routes[routes]
controllers[controllers]
Express[Express]
end

subgraph Layer 3[" "]
services[services]
nodeCache[node-cache]
end

subgraph Layer 4[" "]
database[database]
Sequelize[Sequelize]
end

models[models]

%% Dependencies

app --> server
routes --> app
controllers --> routes
services --> controllers
database --> services

Express --> routes
nodeCache --> services
Sequelize --> database

Express --> app
Express -.-> controllers
Sequelize -.-> models

app -.-> tests

models -.-> database
models -.-> services
models -.-> controllers

controllers --> app
services --> app
database --> app

%% Styling
classDef core fill:#b3d9ff,stroke:#6db1ff,stroke-width:2px,color:#555,font-family:monospace;
classDef deps fill:#ffcccc,stroke:#ff8f8f,stroke-width:2px,color:#555,font-family:monospace;
classDef test fill:#ccffcc,stroke:#53c45e,stroke-width:2px,color:#555,font-family:monospace;

class server,app,routes,controllers,services,database,models core
class Express,Sequelize,nodeCache deps
class tests test
```

### Arrow Semantics

Arrows follow the wiring direction: `A --> B` means A is provided to B. Solid arrows (`-->`) represent active dependencies โ€” modules explicitly wired in `app` and invoked at runtime. Dotted arrows (`-.->`) represent structural dependencies โ€” the consumer references types or interfaces without invoking runtime behavior.

### Composition Root Pattern

`app` is the composition root: it instantiates all dependencies, configures Express middleware, and registers all routes. `server` is separate and owns only the HTTP lifecycle (port binding, graceful shutdown) โ€” a conventional split in Express projects.

### Layered Architecture

Four layers: Initialization (`server`, `app`), HTTP (`routes`, `controllers`), Business (`services`), and Data (`database`).

`models` is a cross-cutting type concern โ€” shared types and Sequelize model definitions consumed across multiple layers, with no business logic of its own.

### Color Coding

Blue = core application packages, red = third-party frameworks, green = tests.

*Simplified, conceptual project structure and main application flow. Not all dependencies are shown.*

## Architecture Decisions

Significant architectural choices โ€” why they were made, what tradeoffs they carry โ€” are documented as Architecture Decision Records (ADRs) in [`docs/adr/`](docs/adr/).

| ADR | Decision |
|-----|----------|
| [001](docs/adr/001-interface-based-architecture.md) | Interface-based architecture with constructor injection |
| [002](docs/adr/002-uuid-primary-key-and-squad-number-mutation-key.md) | UUID as primary key, squadNumber as mutation key |
| [003](docs/adr/003-use-native-esm.md) | Native ESM instead of CommonJS |
| [004](docs/adr/004-use-express-5.md) | Express 5 |
| [005](docs/adr/005-use-sqlite-sequelize.md) | SQLite with Sequelize ORM |
| [006](docs/adr/006-integration-first-testing-strategy.md) | Integration-first testing (real DB, no mocks) |
| [007](docs/adr/007-node-cache-strategy.md) | node-cache with 1-hour TTL |
| [008](docs/adr/008-use-pino-structured-logging.md) | Pino for structured logging |
| [009](docs/adr/009-docker-and-compose-strategy.md) | Multi-stage Docker builds + Compose |
| [010](docs/adr/010-use-tsx-over-ts-node.md) | tsx instead of ts-node |
| [011](docs/adr/011-football-semantic-versioning.md) | Football-themed semantic versioning |

## API Reference

Interactive API documentation is available via Swagger UI at `http://localhost:9000/swagger/` when the server is running.

**Quick Reference:**

- `GET /players` - List all players
- `GET /players/:id` - Get player by ID
- `GET /players/squadNumber/:squadNumber` - Get player by squad number
- `POST /players` - Create new player
- `PUT /players/:id` - Update player
- `DELETE /players/:id` - Remove player
- `GET /health` - Health check

For complete endpoint documentation with request/response schemas, explore the [interactive Swagger UI](http://localhost:9000/swagger/). You can also access the OpenAPI JSON specification at `http://localhost:9000/swagger.json`.

Alternatively, use [`rest/players.rest`](rest/players.rest) with the [REST Client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) extension for VS Code to send requests directly from the editor.

## Prerequisites

Before you begin, ensure you have the following installed:

- Node.js (see `.nvmrc` for required version)
- npm (comes with Node.js)
- [direnv](https://direnv.net/) (optional, but recommended โ€” auto-loads the correct Node.js version via `.nvmrc` on directory entry)
- Docker and Docker Compose (optional, for containerized setup)

## Quick Start

### Clone the repository

```bash
git clone https://github.com/nanotaboada/ts-node-samples-express-restful.git
cd ts-node-samples-express-restful
```

### Install dependencies

```bash
npm install
```

### Start the development server

```bash
npm run dev
```

The server will start on `http://localhost:9000` with the following output:

```console
> ts-node-samples-express-restful@1.0.0 dev
> nodemon

[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `tsx ./src/server.ts`
๐Ÿš€ Running at http://localhost:9000
```

### Access the application

- API: `http://localhost:9000`
- Swagger Documentation: `http://localhost:9000/swagger/`
- Health Check: `http://localhost:9000/health`

## Testing

Run the test suite with Jest:

```bash
# Run all tests
npm test

# Run tests with coverage report
npm run coverage

# Run linter
npm run lint

# Validate commit message format
npm run lint:commit
```

Tests are located in the `tests/` directory and use Supertest for integration testing. Coverage reports are generated for controllers, services, and routes only.

## Containers

This project includes full Docker support with multi-stage builds and Docker Compose for easy deployment.

### Build the Docker image

```bash
npm run docker:build
# or
docker compose build
```

### Start the application

```bash
npm run docker:up
# or
docker compose up
```

> ๐Ÿ’ก **Note:** On first run, the container copies a pre-seeded SQLite database into a persistent volume. On subsequent runs, that volume is reused and the data is preserved.

### Stop the application

```bash
npm run docker:down
# or
docker compose down
```

### Reset the database

To remove the volume and reinitialize the database from the built-in seed file:

```bash
docker compose down -v
```

The containerized application runs on port 9000 and includes health checks that monitor the `/health` endpoint every 30 seconds.

## Releases

This project uses football terminology as release names โšฝ

### Release Naming Convention

Releases follow the pattern: `v{SEMVER}-{TERM}` (e.g., `v1.0.0-assist`)

- **Semantic Version**: Standard versioning (MAJOR.MINOR.PATCH)
- **Term Name**: Alphabetically ordered codename from the [football terminology list](CHANGELOG.md#football-terminology-names-๏ธ)

### Create a Release

To create a new release, follow this workflow:

#### 1. Create a Release Branch

Branch protection prevents direct pushes to `master`, so all release prep goes through a PR:

```bash
git checkout master && git pull
git checkout -b release/vX.Y.Z-term
```

#### 2. Update CHANGELOG.md

Move items from `[Unreleased]` to a new release section in [CHANGELOG.md](CHANGELOG.md), then commit and push the branch:

```bash
# Move items from [Unreleased] to new release section
# Example: [2.0.0 - corner] - 2026-03-29
git add CHANGELOG.md
git commit -m "chore(release): vX.Y.Z-term"
git push origin release/vX.Y.Z-term
```

#### 3. Merge the Release PR

Open a pull request from `release/vX.Y.Z-term` into `master` and merge it. The tag must be created **after** the merge so it points to the correct commit on `master`.

#### 4. Create and Push Tag

After the PR is merged, pull `master` and create the annotated tag:

```bash
git checkout master && git pull
git tag -a vX.Y.Z-term -m "Release X.Y.Z - Term"
git push origin vX.Y.Z-term
```

Example:

```bash
git tag -a v2.0.0-corner -m "Release 2.0.0 - Corner"
git push origin v2.0.0-corner
```

#### 5. Automated CD Workflow

Pushing the tag triggers the CD pipeline which automatically:

1. Builds and tests the project
2. Publishes Docker images to GitHub Container Registry
3. Creates a GitHub Release with auto-generated changelog from commits

#### Pre-Release Checklist

- [ ] Release branch created from `master`
- [ ] `CHANGELOG.md` updated with release notes
- [ ] Changes committed and pushed on the release branch
- [ ] Release PR merged into `master`
- [ ] Tag created with correct format: `vX.Y.Z-term`
- [ ] Term is valid (A-Z from the [football terminology list](CHANGELOG.md#football-terminology-names-๏ธ))
- [ ] Tag pushed to trigger CD workflow

### Pull Docker Images

Each release publishes three Docker tags:

```bash
# By semantic version (recommended for production)
docker pull ghcr.io/nanotaboada/ts-node-samples-express-restful:1.0.0

# By term name (memorable, useful for staging)
docker pull ghcr.io/nanotaboada/ts-node-samples-express-restful:assist

# Latest (development/testing only)
docker pull ghcr.io/nanotaboada/ts-node-samples-express-restful:latest
```

## Environment Variables

Create a `.env` file in the root directory to customize configuration:

```env
# Server port (default: 9000)
PORT=9000

# Database storage path (default: storage/players-sqlite3.db)
# In Docker: /storage/players-sqlite3.db
STORAGE_PATH=storage/players-sqlite3.db

# Rate limiting (all optional โ€” defaults shown)
RATE_LIMIT_ENABLED=true # Set to 'false' to disable rate limiting entirely
RATE_LIMIT_WINDOW_MS=60000 # Time window in milliseconds (default: 1 minute)
RATE_LIMIT_MAX_GENERAL=100 # Max requests per window for all routes
RATE_LIMIT_MAX_STRICT=20 # Max requests per window for POST/PUT/DELETE
```

## Command Summary

| Script | Description |
|------------------------|---------------------------------------------------|
| `npm run dev` | Start development server with hot reload |
| `npm start` | Run compiled application from `dist/` |
| `npm run build` | Compile TypeScript to JavaScript |
| `npm test` | Run Jest tests with --detectOpenHandles flag |
| `npm run coverage` | Generate test coverage report |
| `npm run lint` | Run ESLint on all files |
| `npm run lint:commit` | Validate last commit message format |
| `npm run swagger:docs` | Generate swagger.json from JSDoc annotations |
| `npm run docker:build` | Build Docker image |
| `npm run docker:up` | Start Docker container |
| `npm run docker:down` | Stop and remove Docker volume |

## Contributing

Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the code of conduct and the process for submitting pull requests.

Key guidelines:

- Follow [Conventional Commits](https://www.conventionalcommits.org/) for commit messages
- Ensure all tests pass (`npm test`)
- Run linter before committing (`npm run lint`)
- Keep changes small and focused

## Legal

This project is provided for educational and demonstration purposes and may be used in production at your own discretion. All trademarks, service marks, product names, company names, and logos referenced herein are the property of their respective owners and are used solely for identification or illustrative purposes.