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

@cababunga/router

v0.6.2

Published

Node.js request router and middleware stacker with async/await API and zero dependencies

Downloads

11

Readme

BASE -- Boilerplate API Server Environment

Router

Install

npm i @cababunga/router

Use

HTTP request router and middleware stacker.

Creating router is easy.

const {router} = require("@cababunga/router");
const app = router();

Router has the following methods:

add(methods, route, ...handlers)

methods

This can be the name os a single HTTP method, like "GET" or an array of method names ["GET", "POST"]. Special string "*" means that any method is allowed. If "GET" is allowed, then "HEAD" will be allowed automatically.

route

Route is a path prefix that needs to be matched with the url from request. If segment of route is in form :<word>, this segment won't be matched with the part of the url, instead this part of the url will be available in the handler as request.param[<word>].

handlers

The rest of the parameters are middleware and a handler. The difference between middleware and handler is that middleware doesn't call response.end(). If route only has associated middleware and no final handler, this middleware will be executed for each path for which this route is a prefix.

CORS middleware

Middleware for adding CORS headers.

cors(options)

The following options are recognized:

methods

Will be added as the value for the Access-Control-Allow-Methods header.

origin

Will be added as the value for the Access-Control-Allow-Origin header. If omitted, req.headers["origin"] will be used.

headers

Will be added as the value for the Access-Control-Allow-Headers header.

credentials

Will be added as the value for the Access-Control-Allow-Credentials header.

const cors = require("@cababunga/router/cors");
cors({methods: "GET, POST", headers: "content-type"});

Examples

const http = require("http");
const router = require("@cababunga/router");
const cors = require("@cababunga/router/cors");
const accesslog = require("@cababunga/accesslog");

const response = (res, data, code) => {
    if (data === undefined)
        res.writeHead(code || 204).end();
    else
        res.writeHead(code || 200, {"Content-Type": "application/json"}).end(JSON.stringify(data));
};

const errorResponse = (res, code, message) =>
    res.writeHead(code, {"Content-Type": "application/json"})
        .end(JSON.stringify({err: true, msg: message}));

// Middleware for authentication
const authenticate = async (req, res) => {
    const sessionId = req.headers["x-session-id"];
    const session = await getSession(sessionId);
    if (!session)
        return errorResponse(res, 401, "Please login");
    req.session = session;
};

const getSession = async sessionId => { /* await getSession(sessionId) */ return Promise.resolve(1); };
const listAdd = async (req, res) => { /* await addToList(await req.json()); */ response(res, {ok: true}); };
const listRemove = async (req, res) => { /* await removeFromList(); */ response(res); };

const app = router();
app.all("/", cors({methods: "GET, POST, PATCH, DELETE", headers: "x-session-id, content-type"}));
app.all("/", accesslog(console.log, {skip: "/health-check"}));

app.add("POST", "/api/1/list", authenticate, listAdd);
app.add("DELETE", "/api/1/list/:id", authenticate, listRemove);
app.error((err, req, res) => (res, err) => errorResponse(res, 500, err.message));

http.createServer(app).listen(1234);;