1.1.0 • Published 8 months ago

@fgiova/fastify-rest-gateway v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

fastify rest-gateway

NPM version CI workflow TypeScript

Description

This plugin for fastify 4.x allows you to expose REST APIs for your REST microservices starting from OpenApi contracts hosted into same microservice.

Routes to be exposed by the gateway must be tagged with the appropriate tags; by default "public-api" for public APIs, "private-api" for hidden APIs.

Note To distribute open-api compliant contracts I recommend using the plugins for fastify @fastify/swagger and @fastify/swagger-ui

Warning The plugin mandatorily requires the @fastify/reply-from plugin.

Install

npm i @fgiova/fastify-rest-gateway @fastify/reply-from

Usage

const app = require("fastify")();
const replyFrom = require("@fastify/reply-from");
const fastifyRestGateway = require("@fgiova/fastify-rest-gateway");
app.register(replyFrom);
app.register(fastifyRestGateway, {
    services: [
        {
            host: "https://petstore.test.com",
            openApiUrl: "/open-api/json",
            remoteBaseUrl: "/v1/test/public-api/",
            gwBaseUrl: "/v1/test/",
            
        }
    ]
});

The plugin can be used in conjunction with @fastify/swagger and @fastify/swagger-ui to produce an open-api contract of the routes exposed by the fastify-rest-gateway plugin.

npm i @fgiova/fastify-rest-gateway @fastify/reply-from @fastify/swagger @fastify/swagger-ui
const app = require("fastify")();
const fastifyRestGateway = require("@fgiova/fastify-rest-gateway");

await app.register(require("@fastify/reply-from"));
await app.register(fastifyRestGateway, {
    services: [
        {
            host: "https://petstore.test.com",
            openApiUrl: "/open-api/json",
            remoteBaseUrl: "/v1/test/public-api/",
            gwBaseUrl: "/v1/test/",
            
        }
    ]
});

await app.register(require("@fastify/swagger"), {
    mode: "dynamic",
    openapi: {
        ...
    }
});
await app.register(require("@fastify/swagge-ui"), {
    routePrefix: "/open-api",
});

The plugin can be used in conjunction with @fastify/rate-limit to restrict upstream accesses to the target microservice.

npm i @fgiova/fastify-rest-gateway @fastify/reply-from @fastify/rate-limit
const app = require("fastify")();
const fastifyRestGateway = require("@fgiova/fastify-rest-gateway");

await app.register(require("@fastify/reply-from"));
await app.register(require("@fastify/rate-limit"));
await app.register(fastifyRestGateway, {
    services: [
        {
            host: "https://petstore.test.com",
            openApiUrl: "/open-api/json",
            remoteBaseUrl: "/v1/test/public-api/",
            gwBaseUrl: "/v1/test/",
            hitLimit: {
                max: (req: FastifyRequest) => {
                    return 10;
                },
                keyGenerator: (req: FastifyRequest) => {
                    return `${req.ip}_test`;
                },
                timeWindow: 5000
            }
        }
    ]
});

await app.register(require("@fastify/swagger"), {
    mode: "dynamic",
    openapi: {
        ...
    }
});
await app.register(require("@fastify/swagge-ui"), {
    routePrefix: "/open-api",
});

This plugin can be used in conjunction with @fastify/restartable to reload the routes when open-api contracts of microservices are changed.

npm i @fgiova/fastify-rest-gateway @fastify/reply-from @fastify/rate-limit @fastify/restartable
const app = require("fastify")();
const fastifyRestGateway = require("@fgiova/fastify-rest-gateway");
const restartable = require("@fastify/restartable");


async function createApp (fastify, opts) {
    const app = fastify(opts)

    await app.register(require("@fastify/reply-from"));
    await app.register(require("@fastify/rate-limit"));
    await app.register(fastifyRestGateway, {
        services: [
            {
                host: "https://petstore.test.com",
                openApiUrl: "/open-api/json",
                remoteBaseUrl: "/v1/test/public-api/",
                gwBaseUrl: "/v1/test/",
                refreshTimeout: 60000, // each 60s reload open-api contract from host if are changed, restart fastify
                hitLimit: {
                    max: (req: FastifyRequest) => {
                        return 10;
                    },
                    keyGenerator: (req: FastifyRequest) => {
                        return `${req.ip}_test`;
                    },
                    timeWindow: 5000
                }
            }
        ]
    });

    await app.register(require("@fastify/swagger"), {
        mode: "dynamic",
        openapi: {
            ...
        }
    });
    await app.register(require("@fastify/swagge-ui"), {
        routePrefix: "/open-api",
    });

    return app;
}

const app = await restartable(createApp, { logger: true });
const host = await app.listen({ port: 3000 });

Options

OptionTypeDescription
servicesarrayThe list of services to expose.
services[].hoststringThe host of the service.
services[].openApiUrlstringThe URL of the OpenApi JSON contract (default: /open-api/json).
services[].remoteBaseUrlstringThe baseUrl of the remote service.
services[].gwBaseUrlstringThe baseUrl where the service will be connected on the gateway
services[].tagstringOptional tag for selecting target routes to expose (default: public-api)
services[].hiddenTagstringOptional tag for selecting target routes to expose, but hidden on fastify-swagger (default: private-api)
services[].preHandlerFastifyHandlerOptional Fastify Pre Handler function to add to each service route
services[].hooksobjectOptional hooks for each route exposed
services[].hitLimitobjectOptional limit configuration for each route exposed
defaultLimitobjectOptional default limit configuration
gwTagstringOptional default tag for select target routes to expose (default: public-api)
gwHiddenTagstringOptional default tag for select target routes to expose, but hidden on fastify-swagger (default: X-HIDDEN)
ignoreHiddenbooleanOptional flag to ignore hidden routes
refreshTimeoutnumberOptional interval in ms for watching open-api contracts and reload through Fastify restartable

Service Hooks

OptionTypeDescription
onRequestFastifyHandlerOptional Fastify OnRoute Handler function to add to each service route
onResponseFastifyHandlerOptional Fastify OnResponse Handler function to add to each service route
onErrorFastifyHandlerOptional Fastify OnError Handler function to add to each service route

Service limit options

OptionTypeDescription
maxnumber | functionOptional sync/async Function or number maximum hit per timeWindow (default: 1000)
keyGeneratorfunctionOptional sync/async function to generate a unique identifier for each incoming request (default: req.ip)
timeWindownumberOptional the duration of the time window in ms (default: 60000)

License

Licensed under MIT.

Acknowledgements

This project is kindly sponsored by: isendu Srl www.isendu.com