Skip to content

DDRMin/DIY-expressJS-APIgateway

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

DIY Express.js API Gateway

A lightweight, feature-rich API Gateway built with Express.js and TypeScript, designed for microservices architectures. This gateway provides load balancing, service discovery, authentication, and request routing capabilities.

πŸš€ Features

  • Load Balancing: Multiple strategies including Round Robin and Least Used
  • Service Registry: Dynamic service registration and deregistration
  • Authentication: Basic authentication middleware
  • Security: Helmet.js integration for security headers
  • Health Management: Enable/disable service instances
  • TypeScript: Full TypeScript support with type definitions
  • Hot Reload: Development support with nodemon

πŸ“‹ Table of Contents

πŸ› οΈ Installation

Prerequisites

  • Node.js (v14 or higher)
  • npm or pnpm
  • TypeScript

Setup

  1. Clone the repository:
git clone <your-repo-url>
cd API Gateway
  1. Install dependencies:
npm install
# or
pnpm install
  1. Build the project:
npm run build

πŸš€ Quick Start

Development Mode

npm run dev

The gateway will start on http://localhost:3000

Production Mode

npm run build
npm start

Basic Authentication

All requests require basic authentication:

  • Username: admin
  • Password: password

Include the Authorization header in your requests:

Authorization: YWRtaW46cGFzc3dvcmQ=

βš™οΈ Configuration

Service Registry

Services are managed through the routes/registry.json file. The structure includes:

{
  "services": {
    "serviceName": {
      "loadBalanceStrategy": "ROUND_ROBIN",
      "index": 0,
      "instances": [
        {
          "name": "serviceName",
          "protocol": "http",
          "host": "localhost",
          "port": 3001,
          "url": "http://localhost:3001/",
          "usage": 0,
          "enabled": true
        }
      ]
    }
  }
}

Environment Variables

The gateway runs on port 3000 by default. You can modify this in gateway.ts:

const PORT = 3000;

πŸ“š API Reference

Service Management

Register a Service

POST /register
Content-Type: application/json
Authorization: Basic YWRtaW46cGFzc3dvcmQ=

{
  "name": "user-service",
  "protocol": "http",
  "host": "localhost",
  "port": 3001
}

Deregister a Service

POST /deregister
Content-Type: application/json
Authorization: Basic YWRtaW46cGFzc3dvcmQ=

{
  "name": "user-service",
  "url": "http://localhost:3001/"
}

Enable/Disable Service Instance

POST /enable/:serviceName
Content-Type: application/json
Authorization: Basic YWRtaW46cGFzc3dvcmQ=

{
  "url": "http://localhost:3001/",
  "enabled": true
}

Request Routing

All requests to registered services are automatically routed:

GET /:serviceName/:path
POST /:serviceName/:path
PUT /:serviceName/:path
DELETE /:serviceName/:path

Example:

GET /user-service/api/users

This will be forwarded to one of the registered instances of user-service.

βš–οΈ Load Balancing Strategies

Round Robin (Default)

Distributes requests evenly across all enabled instances in a circular fashion.

{
  "loadBalanceStrategy": "ROUND_ROBIN"
}

Least Used

Routes requests to the instance with the lowest usage count.

{
  "loadBalanceStrategy": "LEAST_USED"
}

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Client App    │────│   API Gateway    │────│  Microservice A β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚                  β”‚    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                       β”‚  β”‚   Auth      β”‚ │────│  Microservice B β”‚
                       β”‚  β”‚ Middleware  β”‚ β”‚    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                       β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” │────│  Microservice C β”‚
                       β”‚  β”‚Load Balancerβ”‚ β”‚    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
                       β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
                       β”‚  β”‚  Registry   β”‚ β”‚
                       β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Components

  • Gateway (gateway.ts): Main Express.js application
  • Routes (routes/index.ts): Request routing and service management
  • Auth (utils/auth.ts): Basic authentication middleware
  • Load Balancer (utils/loadbalancer.ts): Load balancing strategies
  • Registry (routes/registry.json): Service registry database

πŸ”§ Development

Project Structure

β”œβ”€β”€ gateway.ts              # Main application entry point
β”œβ”€β”€ package.json           # Dependencies and scripts
β”œβ”€β”€ tsconfig.json         # TypeScript configuration
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ index.ts          # Route handlers and service management
β”‚   └── registry.json     # Service registry
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ auth.ts          # Authentication middleware
β”‚   └── loadbalancer.ts  # Load balancing algorithms
└── fakeapi/             # Test API for development

Available Scripts

  • npm run dev - Start development server with hot reload
  • npm run build - Build TypeScript to JavaScript
  • npm start - Start production server
  • npm run test - Run tests (if configured)

Adding New Load Balancing Strategies

  1. Add your strategy to utils/loadbalancer.ts:
loadbalancer.CUSTOM_STRATEGY = (service: ServiceEntry) => {
  // Your custom logic here
  // Return the index of the selected instance
  return selectedIndex;
};
  1. Use it in your service configuration:
{
  "loadBalanceStrategy": "CUSTOM_STRATEGY"
}

πŸ’‘ Examples

Example: Complete Setup

  1. Start the Gateway:
npm run dev
  1. Register a Service:
curl -X POST http://localhost:3000/register \
  -H "Content-Type: application/json" \
  -H "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" \
  -d '{
    "name": "user-service",
    "protocol": "http",
    "host": "localhost",
    "port": 3001
  }'
  1. Make Requests Through Gateway:
curl -X GET http://localhost:3000/user-service/api/users \
  -H "Authorization: Basic YWRtaW46cGFzc3dvcmQ="

Example: Multiple Instances with Load Balancing

# Register first instance
curl -X POST http://localhost:3000/register \
  -H "Content-Type: application/json" \
  -H "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" \
  -d '{
    "name": "user-service",
    "protocol": "http",
    "host": "localhost",
    "port": 3001
  }'

# Register second instance
curl -X POST http://localhost:3000/register \
  -H "Content-Type: application/json" \
  -H "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" \
  -d '{
    "name": "user-service",
    "protocol": "http",
    "host": "localhost",
    "port": 3002
  }'

Now requests to /user-service/* will be load-balanced between both instances.

πŸ›‘οΈ Security Features

  • Helmet.js: Automatically sets various HTTP headers for security
  • Basic Authentication: All requests require valid credentials
  • Request Validation: Input validation for service registration
  • Error Handling: Comprehensive error handling with appropriate HTTP status codes

🚧 Roadmap

  • JWT Authentication support
  • Rate limiting
  • Request/Response logging
  • Health checks for registered services
  • Circuit breaker pattern
  • Metrics and monitoring
  • Docker support
  • WebSocket support

🀝 Contributing

  1. Fork the repository
  2. Create your 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

πŸ“„ License

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

πŸ™ Acknowledgments

  • Express.js community for the robust web framework
  • Helmet.js for security middleware
  • TypeScript team for excellent type support

Note: This is a educational/development API Gateway. For production use, consider additional features like SSL termination, advanced authentication, monitoring, and scaling capabilities.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors