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

righty

v1.1.0

Published

Righty - A clean,fast,efficient and the RIGHT way to configure routes in express.js

Downloads

13

Readme

Righty Logo

A clean,fast,efficient and the RIGHT way to configure routes in express.js

NPM

Installation

$ npm install righty

Features

  • Cleaner code
  • Configuration over code (inspired greatly from Hapi)
  • Validations using Joi
  • Automatic swagger documentation generation
  • Body parsing support (json,urlencoded,multipart-formdata)

Quick Start


var express = require('express');
var app = express();
var Joi = require("joi");

var router = require("righty").Router();    // router instance

var Righty = require("righty")({
    defaultContentType : "json",
    swagger : {
        title : "Demo app",
        version : "v1",
        description : "Swagger docs for demo app. Generated using `righty`",
        schemes : ["http"],
        host : "localhost:3000"
    }
});                                       // righty instance

function SendMessageCtrl(req,res) {

    
    // req.body = > { data : "xyz"}
    
    res.send({
        message : "Sent"
    });
}

function ReceiveMessageCtrl(req,res) {

    res.send({
        message: "OK",
        data: ["Hi Foo", "Is Bar der?"]
    });
}


var routeMapping = [

    {
        path : "/message",
        method : "post",
        validate : {
            body : {
                data : Joi.string().max(250)
            }
        },
        handler : SendMessageCtrl
    },

    {
        path : "/message",
        method : "get",
        handler : ReceiveMessageCtrl
    }
];                           

router.add(routeMapping);           // add routes to router

app.use(express.static(__dirname+ '/public'));       // Note : You need to declare public directory as static if swagger documentation required

Righty.use(app,router);          // attach router to app

app.listen(3000);

API

Righty

Exposed by require('righty').

Righty(options)

Creates a new Righty instance.


var Righty = require("righty")({
    defaultContentType : "json",
    swagger : {
        title : "Demo app",
        version : "v1",
        description : "Swagger docs for demo app. Generated using `righty`",
        schemes : ["http"],
        host : "localhost:3000"
    }
});      
  

options

An options object containing following keys has to be passed to instantiate Righty:

  • defaultContentType - The content types to be used for routes, for which content type is not explicitly mentioned. Supported content types (for now) are "json", "urlencoded" and "multipart"

  • swagger - an optional object specifying swagger configuration. If omitted, documentation will not be generated. It may contain following keys:

    • title - title of the documentation. Required
    • version - version of the documentation. Required
    • description - description of the documentation. Optional
    • schemes - The transfer protocol of the API. Values MUST be from the list: "http", "https", "ws", "wss". If the schemes is not included, the default scheme to be used is the one used to access the Swagger definition itself. Optional
    • host - The host (name or ip) serving the API. This MUST be the host only and does not include the scheme nor sub-paths. It MAY include a port. If the host is not included, the host serving the documentation is to be used (including the port) . Optional

Note: You need to declare public directory as static if swagger documentation is required.

Righty.use(app,router)

It mounts Righty router (see below) to express app.

Righty.Router()

Creates a new Righty router instance


var router = require("righty").Router();     
  

router.add(routeMapping)

It mounts route(s) to a Righty router instance. It takes routeMapping as a single argument. routeMapping can be an object or an array of similar objects.

routeMapping

A routeMapping object contains following keys:

  • path - Route path as used in Express. Required
  • method - HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Required
  • contentType - The content type to be associated with the route. If omitted, defaultContentType is used. Optional
  • handler - standard express middleware to be called to generate the response after successful body parsing and validation. Required
  • validate - Object containing validation rules. Optional
    • body - Joi schema object. Optional
    • query - Joi schema object. Optional
    • params - Joi schema object. Optional
    • headers - Joi schema object. Optional
    • files - object containing file names as keys and filePropSchema (see below) as values. Optional
filePropSchema

It is an object containing file validation rules:

  • mimetype - an array of mime-types to be used as filter for the file. Patterns like '*/*', "image/*", etc. are accepted. Required
  • size - Maximum size allowed for files in bytes. Optional

Example where routeMapping is an object:


var router = require("righty").Router();   
  
var controllers = require("../controllers");  

var routeMapping = {
            path : "/profile/:id",
            method : "put",
            validate : {
                body : {
                    name : Joi.string(),
                    gender : Joi.any().valid("m","f")
                },
                headers : {
                    "x-authorization" : Joi.string()
                },
                query : {
                    askForAcknowledgement : Joi.number().valid(0,1),
                },
                params : {
                    id : Joi.number().integer()
                },
                files : {
                    pic : {
                        mimetype : ["image/*"],
                        size : 50000
                    }
                }
            },
            contentType : "multipart",
            handler : controllers.ProfileUpdateCtrl
};

router.add(routeMapping);

module.exports = router;
  

Example where routeMapping is an array:


var router = require("righty").Router();   
  
var controllers = require("../controllers");  

var routeMapping = [
    {
            path : "/profile/:id",
            method : "put",
            validate : {
                body : {
                    name : Joi.string(),
                    gender : Joi.any().valid("m","f")
                },
                headers : {
                    "x-authorization" : Joi.string()
                },
                query : {
                    askForAcknowledgement : Joi.number().valid(0,1),
                },
                params : {
                    id : Joi.number().integer()
                },
                files : {
                    pic : {
                        mimetype : ["image/*"],
                        size : 50000
                    }
                }
            },
            contentType : "multipart",
            handler : controllers.ProfileUpdateCtrl
    },
    {
                path : "/profile/:id",
                method : "get",
                validate : {
                    params : {
                        id : Joi.number().integer()
                    }
                },
                handler : controllers.ProfileViewCtrl
        }
    
];

router.add(routeMapping);

module.exports = router;
  

router.add(basePath,subRouter)

An alternate version of router.add() to facilitate hierarchical routing. subRouter is a normal Righty router and basePath is the path prepended to all the routes in subRouter.

Check out this full blown project which illustrates hierarchical routing.

UPDATE

Now handler can be either middleware or an array of middlewares.

People

The original author of righty is Tabish Rizvi

I am looking for collaborators for this project. Anyone interested can mail be at [email protected]

License

MIT