npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hodfords/nestjs-api-gateway

v10.0.3

Published

The API Gateway houses the source code and documentation for the API Gateway - a powerful and versatile solution for managing and deploying APIs within a distributed and microservices-oriented architecture.

Downloads

54

Readme

API Gateway

The API Gateway houses the source code and documentation for the API Gateway - a powerful and versatile solution for managing and deploying APIs within a distributed and microservices-oriented architecture. This repository serves as the central hub for collaboration, version control, and issue tracking related to the development and enhancement of the API Gateway.

Key Features:

  • Centralized API Management: The API Gateway streamlines API management by providing a central entry point for client applications. It handles API requests, directs traffic to appropriate microservices, and offers additional functionalities to developers and administrators.

  • Security and Authentication: Security is paramount, and the API Gateway offers robust authentication and authorization mechanisms to protect APIs from unauthorized access. It supports various authentication protocols, including API keys, JWT.

  • Rate Limiting and Throttling: To prevent abuse and ensure fair usage, the API Gateway allows administrators to set rate limits and throttling rules. This helps maintain API performance and prevents any single client from overwhelming the system.

  • Logging and Monitoring: The API Gateway provides comprehensive logging and monitoring capabilities, allowing developers and administrators to gain insights into API usage, performance, and errors in real-time.

  • WebSocket Support: Beyond traditional RESTful APIs, the API Gateway supports WebSocket communication for real-time interactions and push notifications.

  • Error Handling and Fault Tolerance: The API Gateway is designed with robust error handling and fault tolerance mechanisms to ensure high availability and reliability.

Usage

Install

npm install @hodfords/api-gateway

Configuration

Import the ApiGatewayModule and use the forRoot method to configure the API Gateway. The forRoot method accepts an options object with the following properties:

@Module({
    imports: [
        RedisModule.forRoot({
            config: {
                host: env.REDIS.HOST,
                port: env.REDIS.PORT,
                db: env.REDIS.DB
            }
        }), // Required
        ScheduleModule.forRoot(), // Required
        ApiGatewayModule.forRoot({
            apiServices: env.API_SERVICES,
            openApiSecurityKeys: ['auth-user-id'],
            excludeHeaders: ['auth-user-id'],
            throttler: {
                globalRateLimit: 60,
                isEnable: true,
                globalRateLimitTTL: 60
            }
        })
    ],
    controllers: [],
    providers: []
})
export class AppModule {}

Custom Authentication Header

You can handle the authentication header by creating a custom authentication handler. The handle method will be called before the request is processed. The handle method accepts the incoming request object and should return a boolean value indicating whether the request is authenticated.

@ProxyMiddleware()
export class AuthenticationMiddleware implements ProxyMiddlewareHandler {
    async handle(routerDetail: RouterDetail, request: IncomingMessage, proxyRequest: ProxyRequest): Promise<boolean> {
        proxyRequest.addHeaders({ 'auth-user-id': '123' });
        return true;
    }
}

Similarly, you can create a WebSocket authentication handler by decorating the @WsProxyMiddleware. The handle method will be called before the request is processed. The handle method accepts the incoming request object and should return a boolean value indicating whether the request is authenticated.

@WsProxyMiddleware()
export class WsAuthenticationMiddleware implements WsProxyMiddlewareHandler {
    async handle(request: IncomingMessage, proxyRequest: ProxyRequest): Promise<boolean> {
        proxyRequest.addHeaders({ 'auth-user-id': '123' });
        return true;
    }
}

Static File

You can create a static file handler by decorating the @StaticRequestHandler. The isStaticRequest method will be called before the request is processed. The isStaticRequest method accepts the incoming request object and should return a boolean value indicating whether the request is for a static file.


@ProxyValidation()
export class StaticRequestMiddleware implements ProxyValidationHandler {
    isStaticRequest(request: IncomingMessage): boolean {
        return request.url.includes('/images/') || request.url.includes('/statics/');
    }
}

Document

API Gateway will aggregate all subservices into one. You can access by the link http://gateway/documents

Authenticate

API Gateway will process the jwt tokens and remove the token from the header. It will then add a new header key to the request called auth-user-id

To define a request that requires authentication, simply use the decorator Auth(). This decorator includes a check header function and a function that adds information to OpenAPI.

In subservices, getting user information is eliminated. Instead you can just get the userId with decorator @CurrentUserId() id: string instead of decorator @CurrentUser()

@Auth()
index(@CurrentUserId() id: string): string {
    return 'Hello word'
}

Rate limit

ApiRateLimit(limit: number, ttl: number, status?: number)

Parameter:

  • limit: number of requests
  • ttl: limited time request
  • status: [optional] limit requests by status, for example you want to limit the number of failed login attempts in 1 minute to 3 times: @ApiRateLimit(3, 60, 401)
@ApiRateLimit(5, 60, 200)
@ApiRateLimit(30, 60 * 60, 200)
@ApiRateLimit(3, 60, 401)
index(): string {
    return 'Hello word'
}

Support:

If you encounter any issues, have questions, or need assistance with the API Gateway, please contact the development team

Thank you for using the API Gateway! Happy API management and development!