Skip to content

Latest commit

 

History

History
487 lines (375 loc) · 11.5 KB

File metadata and controls

487 lines (375 loc) · 11.5 KB

Todo API

A professional, production-ready RESTful Todo API built with TypeScript and Express. This application demonstrates best practices in Node.js development including proper project structure, error handling, validation, testing, and code quality tools.

Features

Core Functionality

  • Full CRUD Operations: Create, Read, Update, and Delete todos
  • Statistics Endpoint: Track completed vs pending todos
  • Type Safety: Written in TypeScript with strict type checking
  • Proper Architecture: Organized with MVC pattern (Models, Controllers, Routes)

API & Documentation

  • Swagger/OpenAPI: Interactive API documentation at /api-docs
  • Request ID Tracking: Unique ID for each request for tracing
  • RESTful Design: Clean, intuitive API endpoints

Security & Performance

  • Security Headers: Helmet.js for secure HTTP headers
  • CORS Support: Cross-Origin Resource Sharing enabled
  • Rate Limiting: Protection against abuse and DDoS
  • Compression: Gzip compression for responses
  • Input Validation: Comprehensive request validation with detailed error messages

Monitoring & Logging

  • Structured Logging: JSON-formatted logs for easy parsing
  • Request Logging: Automatic logging of all requests
  • Error Handling: Centralized error handling middleware
  • Health Check: Endpoint for monitoring service status

Development & Quality

  • Testing: Comprehensive test suite with Jest and Supertest
  • Code Quality: ESLint and Prettier for consistent code style
  • Pre-commit Hooks: Husky and lint-staged for automatic code quality checks
  • CI/CD Pipeline: GitHub Actions for automated testing and deployment
  • Environment Configuration: Dotenv for environment variables

DevOps & Deployment

  • Docker Support: Containerization with multi-stage builds
  • Docker Compose: Easy local development setup
  • Code Security: CodeQL analysis and Dependabot
  • EditorConfig: Consistent coding styles across editors

Project Structure

todo-api/
├── src/
│   ├── config/           # Configuration files
│   │   └── env.config.ts
│   ├── controllers/      # Request handlers
│   │   └── todo.controller.ts
│   ├── middleware/       # Express middleware
│   │   ├── error.middleware.ts
│   │   ├── logger.middleware.ts
│   │   └── validation.middleware.ts
│   ├── models/          # Data models
│   │   └── todo.model.ts
│   ├── routes/          # API routes
│   │   ├── index.ts
│   │   └── todo.routes.ts
│   ├── types/           # TypeScript type definitions
│   │   ├── express.types.ts
│   │   └── todo.types.ts
│   ├── utils/           # Utility functions
│   │   └── logger.ts
│   ├── app.ts           # Express app configuration
│   └── server.ts        # Server entry point
├── tests/               # Test files
│   └── todo.test.ts
├── .env.example         # Environment variables template
├── .eslintrc.json       # ESLint configuration
├── .prettierrc          # Prettier configuration
├── jest.config.js       # Jest configuration
├── tsconfig.json        # TypeScript configuration
└── package.json         # Project dependencies and scripts

Prerequisites

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

Installation

  1. Clone the repository

    git clone https://github.com/UNC-GDSC/ToDo-APIs.git
    cd ToDo-APIs
  2. Install dependencies

    npm install
  3. Set up environment variables

    cp .env.example .env

    Edit .env file with your configuration:

    NODE_ENV=development
    PORT=3000
    API_PREFIX=/api

Usage

Development Mode

Run the application with auto-reload on file changes:

npm run dev

Production Mode

Build and run the compiled application:

npm run build
npm start

The server will start on http://localhost:3000 (or your configured PORT).

Docker

Run the application using Docker:

# Build the Docker image
docker build -t todo-api .

# Run the container
docker run -p 3000:3000 --env-file .env todo-api

# Or use Docker Compose
docker-compose up

# Stop the container
docker-compose down

Access the application at http://localhost:3000.

API Documentation

Interactive Documentation

Access the Swagger UI documentation at:

http://localhost:3000/api-docs

The Swagger UI provides:

  • Complete API reference with request/response examples
  • Interactive testing of all endpoints
  • Schema definitions for all data models
  • Try-it-out functionality for each endpoint

Base URL

Base URL: http://localhost:3000/api

Health Check

GET /health

Check if the API is running.

Response:

{
  "success": true,
  "message": "Todo API is running",
  "timestamp": "2025-11-13T12:00:00.000Z"
}

Todo Endpoints

Get All Todos

GET /todos

Response:

{
  "success": true,
  "data": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "title": "Buy groceries",
      "description": "Milk, eggs, bread",
      "completed": false,
      "createdAt": "2025-11-13T12:00:00.000Z",
      "updatedAt": "2025-11-13T12:00:00.000Z"
    }
  ],
  "message": "Retrieved 1 todos"
}

Get Todo by ID

GET /todos/:id

Response:

{
  "success": true,
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "title": "Buy groceries",
    "description": "Milk, eggs, bread",
    "completed": false,
    "createdAt": "2025-11-13T12:00:00.000Z",
    "updatedAt": "2025-11-13T12:00:00.000Z"
  }
}

Create Todo

POST /todos

Request Body:

{
  "title": "Buy groceries",
  "description": "Milk, eggs, bread"
}

Validation Rules:

  • title (required): String, 1-200 characters
  • description (optional): String, max 1000 characters

Response: (201 Created)

{
  "success": true,
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "title": "Buy groceries",
    "description": "Milk, eggs, bread",
    "completed": false,
    "createdAt": "2025-11-13T12:00:00.000Z",
    "updatedAt": "2025-11-13T12:00:00.000Z"
  },
  "message": "Todo created successfully"
}

Update Todo

PUT /todos/:id

Request Body:

{
  "title": "Buy groceries and cook dinner",
  "description": "Updated description",
  "completed": true
}

Validation Rules:

  • At least one field must be provided
  • title (optional): String, 1-200 characters
  • description (optional): String, max 1000 characters
  • completed (optional): Boolean

Response:

{
  "success": true,
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "title": "Buy groceries and cook dinner",
    "description": "Updated description",
    "completed": true,
    "createdAt": "2025-11-13T12:00:00.000Z",
    "updatedAt": "2025-11-13T12:05:00.000Z"
  },
  "message": "Todo updated successfully"
}

Delete Todo

DELETE /todos/:id

Response:

{
  "success": true,
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "title": "Buy groceries",
    "description": "Milk, eggs, bread",
    "completed": true,
    "createdAt": "2025-11-13T12:00:00.000Z",
    "updatedAt": "2025-11-13T12:05:00.000Z"
  },
  "message": "Todo deleted successfully"
}

Get Statistics

GET /todos/stats

Response:

{
  "success": true,
  "data": {
    "total": 10,
    "completed": 6,
    "pending": 4
  }
}

Error Responses

All error responses follow this format:

{
  "success": false,
  "error": "Error message description"
}

Common HTTP status codes:

  • 400 - Bad Request (validation errors)
  • 404 - Not Found
  • 500 - Internal Server Error

Development

Available Scripts

  • npm run dev - Start development server with auto-reload
  • npm run build - Compile TypeScript to JavaScript
  • npm run build:clean - Clean build directory and rebuild
  • npm start - Run compiled application
  • npm test - Run test suite with coverage
  • npm run test:watch - Run tests in watch mode
  • npm run lint - Check code for linting errors
  • npm run lint:fix - Fix linting errors automatically
  • npm run format - Format code with Prettier
  • npm run format:check - Check code formatting

Running Tests

# Run all tests with coverage
npm test

# Run tests in watch mode
npm run test:watch

Test coverage report will be generated in the coverage/ directory.

Code Quality

This project uses ESLint and Prettier for code quality and formatting:

# Check for linting issues
npm run lint

# Fix linting issues
npm run lint:fix

# Format code
npm run format

Architecture

Models

  • todo.model.ts: In-memory data store and business logic for todos

Controllers

  • todo.controller.ts: Request handlers for todo operations

Routes

  • todo.routes.ts: Todo endpoint definitions
  • index.ts: Main router combining all routes

Middleware

  • error.middleware.ts: Centralized error handling
  • logger.middleware.ts: Request/response logging
  • validation.middleware.ts: Input validation

Types

  • todo.types.ts: Todo-related TypeScript interfaces
  • express.types.ts: Express-related TypeScript types

Configuration

  • env.config.ts: Environment variable management and validation

Environment Variables

Variable Description Default
NODE_ENV Environment (development/production) development
PORT Server port 3000
API_PREFIX API route prefix /api

CI/CD

This project includes automated CI/CD pipelines using GitHub Actions:

Continuous Integration

  • Automated Testing: Runs on every push and pull request
  • Multi-version Testing: Tests against Node.js 16, 18, and 20
  • Code Quality Checks: Linting and formatting verification
  • Security Audits: npm audit for dependency vulnerabilities
  • Code Coverage: Automated coverage reports with Codecov

Security Scanning

  • CodeQL Analysis: Automated code security scanning
  • Dependabot: Automatic dependency updates
  • Vulnerability Alerts: Real-time security notifications

Workflows

View the workflows in .github/workflows/:

  • ci.yml - Main CI/CD pipeline
  • codeql.yml - Security analysis

Future Enhancements

Completed ✅

  • Rate limiting
  • API documentation with Swagger/OpenAPI
  • Docker containerization
  • CI/CD pipeline

Planned

  • Database integration (MongoDB, PostgreSQL)
  • User authentication and authorization (JWT, OAuth)
  • Pagination for todo lists
  • Advanced filtering and sorting
  • WebSocket support for real-time updates
  • GraphQL API option
  • Caching layer (Redis)
  • Metrics and monitoring (Prometheus, Grafana)
  • Kubernetes deployment manifests

Contributing

We welcome contributions! Please see CONTRIBUTING.md for detailed guidelines.

Quick start:

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

Please read our Code of Conduct before contributing.

License

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

Author

GDSC-UNC


Built with TypeScript, Express, and best practices in mind.