Skip to content

Modern REST API built with Fastify and TypeScript featuring dependency injection, comprehensive testing, and production-ready architecture

License

Notifications You must be signed in to change notification settings

NeaDigitra/Fastify-TS-API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Fastify TypeScript API

TypeScript Fastify Node.js Vitest

A modern, high-performance REST API built with Fastify and TypeScript, featuring dependency injection, comprehensive testing, and production-ready architecture.

✨ Features

  • πŸš€ High Performance - Built with Fastify for exceptional speed
  • πŸ”’ Type Safety - Full TypeScript implementation with strict typing
  • πŸ—οΈ Clean Architecture - Modular design with dependency injection
  • πŸ§ͺ Comprehensive Testing - 87% test coverage with Vitest
  • πŸ“š API Documentation - Auto-generated OpenAPI/Swagger docs
  • πŸ›‘οΈ Security First - Built-in security headers, CORS, and rate limiting
  • πŸ”§ Developer Experience - Hot reload, linting, and pre-commit hooks
  • πŸ“Š Production Ready - Structured logging, error handling, and graceful shutdown

πŸš€ Quick Start

Prerequisites

  • Node.js >= 18.0.0
  • npm >= 8.0.0

Installation

# Clone the repository
git clone https://github.com/NeaDigitra/Fastify-TS-API.git
cd Fastify-TS-API

# Install dependencies
npm install

# Start development server
npm run dev

The API will be available at http://localhost:3000

API Documentation

Once the server is running, visit:

  • Swagger UI: http://localhost:3000/docs
  • OpenAPI JSON: http://localhost:3000/docs/json

πŸ“ Project Structure

src/
β”œβ”€β”€ config/           # Configuration and environment variables
β”‚   β”œβ”€β”€ constants.ts  # API constants and HTTP codes
β”‚   β”œβ”€β”€ environment.ts # Environment validation with Zod
β”‚   β”œβ”€β”€ messages.ts   # Centralized message templates
β”‚   └── sample-data.ts # Sample data generation
β”œβ”€β”€ container/        # Dependency injection setup
β”‚   └── container.ts  # Awilix DI container configuration
β”œβ”€β”€ controllers/      # HTTP request handlers
β”‚   β”œβ”€β”€ health.controller.ts
β”‚   └── user.controller.ts
β”œβ”€β”€ middleware/       # Custom middleware
β”‚   β”œβ”€β”€ error-handler.ts
β”‚   └── request-logger.ts
β”œβ”€β”€ repositories/     # Data access layer
β”‚   β”œβ”€β”€ user.repository.ts
β”‚   └── impl/
β”‚       └── in-memory-user.repository.ts
β”œβ”€β”€ routes/          # Route definitions
β”‚   β”œβ”€β”€ health.ts
β”‚   └── users.ts
β”œβ”€β”€ schemas/         # TypeBox validation schemas
β”‚   β”œβ”€β”€ health.schema.ts
β”‚   β”œβ”€β”€ response.schema.ts
β”‚   └── user.schema.ts
β”œβ”€β”€ services/        # Business logic layer
β”‚   └── user.service.ts
β”œβ”€β”€ types/           # TypeScript type definitions
β”‚   └── index.ts
β”œβ”€β”€ utils/           # Utility functions
β”‚   β”œβ”€β”€ errors.ts
β”‚   β”œβ”€β”€ id-generator.ts
β”‚   └── response.ts
└── index.ts         # Application entry point

πŸ”§ Available Scripts

# Development
npm run dev          # Start development server with hot reload
npm run build        # Build for production
npm start            # Start production server

# Testing
npm test             # Run tests
npm run test:watch   # Run tests in watch mode
npm run test:coverage # Run tests with coverage report

# Code Quality
npm run lint         # Run ESLint
npm run lint:fix     # Fix ESLint issues
npm run format       # Format code with Prettier
npm run typecheck    # Run TypeScript type checking

πŸ“‘ API Endpoints

Health Check

  • GET /api/v1/health - Basic health check
  • GET /api/v1/health/ready - Readiness check with service status

User Management

  • GET /api/v1/users - List all users (with pagination)
  • GET /api/v1/users/:id - Get user by ID
  • POST /api/v1/users - Create new user
  • PUT /api/v1/users/:id - Update user
  • DELETE /api/v1/users/:id - Delete user

πŸ—οΈ Architecture

Clean Architecture Layers

graph TD
    A[Controllers] --> B[Services]
    B --> C[Repositories]
    C --> D[Data Sources]

    E[Routes] --> A
    F[Middleware] --> E
    G[Schemas] --> A
    H[Utils] --> B
Loading

Dependency Injection

The application uses Awilix for dependency injection, enabling:

  • Loose coupling between components
  • Easy testing with mock dependencies
  • Scalable and maintainable architecture

Error Handling

Custom error hierarchy with proper HTTP status codes:

  • AppError - Base error class
  • NotFoundError - 404 errors
  • ValidationError - 400 validation errors
  • DuplicateResourceError - 409 conflict errors
  • And more...

πŸ§ͺ Testing

The project includes comprehensive testing with 87% coverage:

# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Watch mode for development
npm run test:watch

Testing Strategy

  • Unit Tests - Individual component testing
  • Integration Tests - API endpoint testing
  • Error Scenario Testing - Edge cases and error handling
  • Repository Testing - Data layer testing

βš™οΈ Configuration

Environment Variables

Create a .env file in the root directory:

# Server Configuration
NODE_ENV=development
PORT=3000
HOST=0.0.0.0
LOG_LEVEL=info

# API Configuration
API_PREFIX=/api/v1
APP_NAME=Fastify TS API
APP_VERSION=1.0.0
API_DESCRIPTION=A modern REST API built with Fastify and TypeScript

# Rate Limiting
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW=60000

# Pagination
PAGINATION_DEFAULT_PAGE=1
PAGINATION_DEFAULT_LIMIT=10
PAGINATION_MAX_LIMIT=100

# Features
ENABLE_SAMPLE_DATA=true

Configuration Schema

All environment variables are validated using Zod with:

  • Type coercion (string to number/boolean)
  • Default values
  • Validation rules
  • Runtime type safety

πŸ›‘οΈ Security Features

  • Helmet - Security headers
  • CORS - Cross-origin resource sharing
  • Rate Limiting - Request throttling
  • Input Validation - Schema-based validation
  • Error Sanitization - Safe error responses

πŸ“Š Monitoring & Logging

Structured Logging

Using Pino for high-performance logging:

  • Request/response logging
  • Error tracking with stack traces
  • Configurable log levels
  • Pretty printing for development

Health Checks

  • Basic health endpoint
  • Readiness checks with service status
  • Graceful shutdown handling

πŸš€ Deployment

Docker (Recommended)

# Example Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
EXPOSE 3000
CMD ["npm", "start"]

Build for Production

# Build the application
npm run build

# Start production server
npm start

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Follow TypeScript best practices
  • Maintain test coverage above 85%
  • Use conventional commit messages
  • Ensure all linting rules pass
  • Update documentation for new features

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Fastify - Fast and low overhead web framework
  • TypeScript - JavaScript with types
  • Vitest - Blazing fast unit testing framework
  • Awilix - Dependency injection container

πŸ“ž Support

If you have any questions or need help getting started:

  1. Check the API Documentation
  2. Review the examples
  3. Open an issue

Happy coding! πŸŽ‰

About

Modern REST API built with Fastify and TypeScript featuring dependency injection, comprehensive testing, and production-ready architecture

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •