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

https://github.com/ebukaodini/express-api-template

an express typescript api template
https://github.com/ebukaodini/express-api-template

expressjs low-code restapi-framework typescript validation-library

Last synced: 7 days ago
JSON representation

an express typescript api template

Awesome Lists containing this project

README

          

# Express TypeScript API Template

A robust, production-ready Express.js API template built with TypeScript, featuring comprehensive testing, documentation, and modern development practices.

## ๐Ÿš€ Features

- **TypeScript** - Full type safety and modern JavaScript features
- **Express.js** - Fast, unopinionated web framework
- **Central Entry Point** - Robust application architecture with dependency injection
- **Prisma** - Modern database toolkit with type-safe queries
- **Jest** - Comprehensive testing suite with unit and integration tests
- **Swagger/OpenAPI** - Interactive API documentation
- **Winston** - Structured logging
- **Rate Limiting** - Built-in request rate limiting
- **Security** - Helmet.js for security headers
- **Validation** - Class-validator for request validation
- **Error Handling** - Custom error classes and centralized error handling
- **Environment Configuration** - Centralized config management
- **Docker Support** - Ready for containerization
- **Code Quality** - Prettier, ESLint, and TypeScript strict mode

## ๐Ÿ“ Project Structure

```
src/
โ”œโ”€โ”€ app/ # Central entry point architecture
โ”‚ โ”œโ”€โ”€ application.ts # Main application class
โ”‚ โ””โ”€โ”€ service-registry.ts # Service management
โ”œโ”€โ”€ bootstrap/ # Configuration management
โ”‚ โ”œโ”€โ”€ app.ts # Express app setup
โ”‚ โ”œโ”€โ”€ config.ts # Main application class
โ”‚ โ”œโ”€โ”€ errors.ts # Custom error classes
โ”‚ โ”œโ”€โ”€ modules.ts # Main application class
โ”‚ โ”œโ”€โ”€ seeders.ts # Main application class
โ”‚ โ””โ”€โ”€ services.ts # Main application class
โ”œโ”€โ”€ features/ # Feature-based modules
โ”‚ โ””โ”€โ”€ user/ # User feature module
โ”‚ โ”œโ”€โ”€ user.controller.ts
โ”‚ โ”œโ”€โ”€ user.service.ts
โ”‚ โ”œโ”€โ”€ user.repo.ts
โ”‚ โ”œโ”€โ”€ user.dto.ts
โ”‚ โ””โ”€โ”€ user.entity.ts
โ”œโ”€โ”€ middlewares/ # Express middlewares
โ”œโ”€โ”€ services/ # Shared services
โ”œโ”€โ”€ utils/ # Utility functions
โ”œโ”€โ”€ server.ts # Central entry point
โ”œโ”€โ”€ __tests__/ # Test files
โ”‚ โ”œโ”€โ”€ unit/ # Unit tests
โ”‚ โ”œโ”€โ”€ integration/ # Integration tests
โ”‚ โ””โ”€โ”€ prisma.config.ts # Test configuration
```

## ๐Ÿ› ๏ธ Setup

### Prerequisites

- Node.js (v18 or higher)
- PostgreSQL (v12 or higher)
- npm or yarn

### 1. Clone the repository

```bash
npx degit https://github.com/ebukaodini/express-api-template.git my-api
cd my-api
```

### 2. Install dependencies

```bash
pnpm install
```

### 3. Environment Configuration

Create a `.env` file in the root directory:

```bash
cp .env.example .env
```

Update the environment variables:

```env
# Server Configuration
PORT=3000
NODE_ENV=development

# Database Configuration
DATABASE_URL="postgresql://username:password@localhost:5432/sample_api"

# CORS Configuration
CORS_ORIGIN="http://localhost:3000,http://localhost:3001"
CORS_CREDENTIALS=true

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX=100

# JWT Configuration
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"
JWT_EXPIRES_IN="24h"

# Logging
LOG_LEVEL="debug"
```

### 4. Database Setup

```bash
# Generate Prisma client
pnpm prisma:generate

# Run database migrations
pnpm prisma:migrate

# Seed the database (optional)
pnpm seed:dev
```

### 5. Start the development server

**Traditional way:**
```bash
pnpm dev
```

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

## ๐Ÿ“š API Documentation

Once the server is running, you can access the interactive API documentation at:

- **Swagger UI**: `http://localhost:3000/api-docs`
- **Health Check**: `http://localhost:3000/health`

## ๐Ÿงช Testing

### Run all tests

```bash
pnpm test
```

### Run tests in watch mode

```bash
pnpm run test:watch
```

### Run tests with coverage

```bash
npm run test:coverage
```

### Run integration tests only

```bash
npm run test:integration
```

## ๐Ÿ“ Available Scripts

| Script | Description |
|--------|-------------|
| `npm run dev` | Start development server with hot reload |
| `npm run build` | Build the project for production |
| `npm start` | Start production server |
| `npm test` | Run all tests |
| `npm run test:watch` | Run tests in watch mode |
| `npm run test:coverage` | Run tests with coverage report |
| `npm run test:integration` | Run integration tests only |
| `npm run test:central` | Run central entry point tests |
| `npm run example` | Run central entry point examples |
| `npm run start:central` | Start with central entry point |
| `npm run dev:central` | Development with central entry point |
| `npm run lint` | Format code with Prettier |
| `npm run lint:check` | Check code formatting |
| `npm run prisma:migrate` | Run database migrations |
| `npm run prisma:generate` | Generate Prisma client |
| `npm run prisma:seed` | Seed the database |
| `npm run docs` | Display API documentation info |

## ๐Ÿ—๏ธ Architecture

### Central Entry Point Architecture

This template implements a robust central entry point architecture that provides:

- **Application Class** - Main orchestrator for application lifecycle
- **Dependency Injection** - Container-based service management
- **Service Registry** - Centralized service lifecycle management
- **Service Factory** - Factory pattern for service creation
- **Health Monitoring** - Comprehensive service health checks

### Feature-Based Structure

The project follows a feature-based architecture where each feature is self-contained with its own:

- **Controller** - Handles HTTP requests and responses
- **Service** - Contains business logic
- **Repository** - Handles data access
- **DTO** - Data transfer objects for validation
- **Entity** - Domain models
- **Routes** - API route definitions

### Error Handling

- Custom error classes for different error types
- Centralized error handling middleware
- Structured error responses
- Proper HTTP status codes

### Logging

- Winston logger with multiple transports
- Structured logging with timestamps
- Different log levels for different environments
- Request/response logging

### Security

- Helmet.js for security headers
- CORS configuration
- Rate limiting
- Input validation
- SQL injection protection (via Prisma)

## ๐Ÿš€ Deployment

### Docker

```bash
# Build the Docker image
docker build -t my-api .

# Run the container
docker run -p 3000:3000 my-api
```

### Environment Variables for Production

Make sure to set the following environment variables in production:

- `NODE_ENV=production`
- `DATABASE_URL` - Your production database URL
- `JWT_SECRET` - A strong, random secret key
- `CORS_ORIGIN` - Your production frontend URL
- `LOG_LEVEL=info`

## ๐Ÿค Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for your changes
5. Ensure all tests pass
6. Submit a pull request

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- Built with [scaffold.js](https://www.npmjs.com/package/@ebukaodini/scaffold.js)
- Inspired by modern Node.js best practices
- Community contributions and feedback