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

@wistle/router

v1.0.2

Published

This package is to handle http server

Downloads

6

Readme

Wistle Router

A simple and flexible router wrapper for Fastify, allowing you to easily add routes and middlewares in a structured manner.

Table of Contents

Installation

To install the package, use npm or yarn:

npm install @wistle/router

Usage

Basic Setup

First, create a server instance and start it. The following code shows how to start the Fastify server.

// app.js
import { Server } from './lib/server';

(async () => {
    try {
        await new Server().start();
    } catch (err) {
        console.error("Wistle Router: error on server start", err);
        process.exit(1);
    }
})();

Defining a Controller

Define your controller methods, which will handle the incoming requests.

// controllers/HealthCheckController.js
class HealthCheckController {
    async check(req, res) {
        res.send({ status: "OK" });
    }

    async fail(req, res) {
        res.status(400).send({ status: "FAIL" });
    }
}

module.exports = HealthCheckController;

Creating and Registering a Router

Extend the Router class to define your routes and apply middlewares if needed.

// routes/HealthCheckRouter.js
const { Router } = require('@wistle/router');
const HealthCheckController = require('../controllers/HealthCheckController');

class HealthCheckRouter extends Router {
    route = "/health"; // Base path for all routes in this router

    setRoutes() {
        const controller = new HealthCheckController();
        this.addRoute("GET", "/check", controller.check);
        this.addRoute("POST", "/fail", controller.fail);
    }
}

module.exports = HealthCheckRouter;

Register the router with your Fastify instance. This can be done in the server setup file.

Middleware

You can define and use middleware functions to process requests before they reach your controllers.

// middlewares/logRequest.js
function logRequest(req, res, next) {
    console.log(`Request received: ${req.method} ${req.url}`);
    next();
}

module.exports = logRequest;

Apply middleware to the router or specific routes:

// routes/HealthCheckRouter.js
const { Router } = require('@wistle/router');
const HealthCheckController = require('../controllers/HealthCheckController');
const logRequest = require('../middlewares/logRequest');

class HealthCheckRouter extends Router {
    route = "/health";
    middleWares = [logRequest]; // Apply middleware to all routes in this router

    initRoutes() {
        const controller = new HealthCheckController();
        this.addRoute("GET", "/check", controller.check, [logRequest]); // Apply middleware to a specific route
        this.addRoute("POST", "/fail", controller.fail);
    }
}

module.exports = HealthCheckRouter;
// routes/index.js
const HealthCheckRouter = require('./HealthCheckRouter');

const Routes = [
    HealthCheckRouter
];

module.exports = {
    Routes
}

Run the server

node app.js

Custom Initializer

In the server setup, you have the option to specify a custom initializer function that can be used to initialize any database or cache-related operations asynchronously. This function should be located at /config/initializer and should export an async function.

Here's how to set it up:

Step 1: Create the Custom Initializer

Create a file at /config/initializer.js (or .ts for TypeScript) and export an async function that handles your initialization logic httpServer is optional node http module param to handle socket connections.

// config/initializer.js
module.exports = async function customInit(httpServer) {
    // Example: Initialize database connection
    await initializeDatabase();

    // Example: Initialize cache
    await initializeCache();

    console.log('Custom initialization completed.');
};

// Example functions (implement your actual initialization logic)
async function initializeDatabase() {
    // Database initialization logic
    console.log('Database initialized.');
}

async function initializeCache() {
    // Cache initialization logic
    console.log('Cache initialized.');
}

Custom Graceful Shutdown Configuration

In your server setup, you have the flexibility to define a custom graceful shutdown function to handle cleanup tasks such as closing database connections or releasing resources. This function should be located at /config/grace and should export a function.

Here's how to set it up:

Step 1: Create the Custom Graceful Shutdown Function

Create a file at /config/grace.js (or .ts for TypeScript) and export a function that performs your cleanup tasks asynchronously.

// config/grace.js
module.exports = async function customGraceShutdown() {
    // Example: Close database connections
    await closeDatabaseConnection();

    // Example: Clean up resources
    await cleanupResources();

    console.log('Custom graceful shutdown completed.');
};

// Example functions (implement your actual cleanup logic)
async function closeDatabaseConnection() {
    // Database connection closing logic
    console.log('Closing database connection.');
}

async function cleanupResources() {
    // Resource cleanup logic
    console.log('Cleaning up resources.');
}

In this package server setup,there is a logic to execute the custom graceful shutdown function when handling shutdown signals like SIGINT or SIGTERM.

Logging

Please refer @wistle/logger for logging Docs.

Logging Usage

Logger is global object. Simply refer below snippet anywhere in code after Server.start():

Logger.verbose(operationId, message, params, param2, ...)

Config

use config.json (Prod) or config_dev.json file at the root folder.

{
    "port": 3000,
    "trustProxy": true,
    "connectionTimeout": 30000,
    "keepAliveTimeout": 72000,
    "headersTimeout": 60000,
    "cors": {
        "origin": "*",
        "methods": ["GET", "POST", "PUT", "DELETE"],
        "allowedHeaders": ["Content-Type", "Authorization", "wistle-operation-id"],
        "credentials": true
    },
    "logger": {
        "writeToConsole": true,
        "writeToFile": false,
        "writeToElk": false,
        "elkOptions": { },
        "fileOptions": {
            "fileName": "test.log",
            "flags": "a"
        },
        "label": "wistle-user-api"
    }
}

License

This project is licensed under the MIT License.