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

smart-api-gateway-js

v1.0.0

Published

A customizable and feature-rich API gateway with security features, rate limiting, and more. Built with Node.js.

Downloads

5

Readme

Smart API Gateway

Smart API Gateway is a robust API Gateway for Node.js, offering essential middleware functionalities and advanced features like AI-powered request routing and real-time analytics.

Installation

Install the package via npm:

npm install smart-api-gateway-js

Basic Setup

  1. Create an Express Application

    Set up a new Express application and integrate the Smart API Gateway:

    import express from 'express';
    import dotenv from 'dotenv';
    import { loadMiddlewares, loadRoutes } from 'smart-api-gateway-js/src/utils/loader.js';
    import { aiRoutingMiddleware } from 'smart-api-gateway-js/src/middlewares/aiRoutingMiddleware.js'; 
    
    dotenv.config();
    
    const app = express();
    const PORT = process.env.PORT || 4000;
    
    app.use(express.json());
    
    // Load AI routing middleware if enabled
    if (process.env.ENABLE_AI_ROUTING === 'true') {
      app.use(aiRoutingMiddleware);
    }
    
    // Load other middlewares and routes
    loadMiddlewares(app);
    loadRoutes(app);
    
    app.listen(PORT, () => {
      console.log(`API Gateway running on port ${PORT}`);
    });
  2. Configure Environment Variables

    Create a .env file in your project root with the following configuration:

    PORT=4000
    ENABLE_SECURITY_MIDDLEWARE=true
    ENABLE_RATE_LIMIT_MIDDLEWARE=true
    ENABLE_CORS_MIDDLEWARE=true
    ENABLE_LOGGING_MIDDLEWARE=true
    ENABLE_AI_ROUTING=true
    ENABLE_ANALYTICS=true
    ENCRYPTION_KEY=your_encryption_key_here

Features

AI-Powered Request Routing

The AI-powered request routing middleware dynamically routes requests based on predictions from an AI model.

  1. Add Your AI Model

    Place your AI model file (e.g., model.json) in an accessible directory.

  2. Set Up AI Middleware

    Ensure your AI middleware is configured correctly to use your AI model.

    middlewares/aiRoutingMiddleware.js

    import * as tf from '@tensorflow/tfjs';
    
    let model;
    async function loadModel() {
      model = await tf.loadLayersModel('file://path/to/your/model.json');
    }
    loadModel();
    
    export async function aiRoutingMiddleware(req, res, next) {
      try {
        const features = [req.headers['user-agent'].length, req.body.length];
        const prediction = model.predict(tf.tensor([features])).dataSync();
        req.route = prediction > 0.5 ? '/route1' : '/route2'; // Customize routing logic as needed
        next();
      } catch (error) {
        next(error);
      }
    }

Real-Time Analytics Dashboard

Monitor your API's performance with a real-time analytics dashboard.

  1. Set Up Analytics Server

    analytics/analyticsServer.js

    import http from 'http';
    import socketIo from 'socket.io';
    
    const server = http.createServer();
    const io = socketIo(server);
    
    io.on('connection', (socket) => {
      console.log('A user connected');
      setInterval(() => {
        socket.emit('analytics', { requestsPerMinute: Math.random() * 100, errorRate: Math.random() * 10 });
      }, 1000);
    
      socket.on('disconnect', () => {
        console.log('User disconnected');
      });
    });
    
    server.listen(3001, () => {
      console.log('Analytics server running on port 3001');
    });
  2. Create Analytics Dashboard

    public/dashboard.html

    <!DOCTYPE html>
    <html>
    <head>
      <title>Real-Time Analytics Dashboard</title>
      <script src="/socket.io/socket.io.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    </head>
    <body>
      <h1>API Analytics Dashboard</h1>
      <canvas id="chart" width="400" height="200"></canvas>
    
      <script>
        const socket = io('http://localhost:3001');
        const ctx = document.getElementById('chart').getContext('2d');
    
        const chart = new Chart(ctx, {
          type: 'line',
          data: {
            labels: [],
            datasets: [{
              label: 'Requests Per Minute',
              data: [],
              borderColor: 'rgba(75, 192, 192, 1)',
              borderWidth: 1,
              fill: false
            }]
          },
          options: {
            scales: {
              x: { type: 'time', time: { unit: 'minute' } },
              y: { beginAtZero: true }
            }
          }
        });
    
        socket.on('analytics', (data) => {
          const now = new Date();
          chart.data.labels.push(now);
          chart.data.datasets[0].data.push(data.requestsPerMinute);
          chart.update();
        });
      </script>
    </body>
    </html>
  3. Serve Dashboard

    Ensure your Express server serves the static files:

    server.js

    import express from 'express';
    import path from 'path';
    import { loadMiddlewares, loadRoutes } from './utils/loader.js';
    
    const app = express();
    const PORT = process.env.PORT || 4000;
    
    app.use(express.json());
    app.use(express.static(path.join(__dirname, 'public')));
    
    loadMiddlewares(app);
    loadRoutes(app);
    
    app.listen(PORT, () => {
      console.log(`API Gateway running on port ${PORT}`);
    });

    Access the dashboard at:

    http://localhost:4000/dashboard.html

License

MIT License.