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

micro-r

v2.0.6

Published

file structure based router for micro

Downloads

49

Readme

npm version types size coverage Dependencies devDependencies License

file structure based router for micro/express


Installation

$ npm i micro-r

About

micro-r is a small and opinionated routing library utilizing file/folder of the application. Routes are not dynamic and are bound at runtime, rendering "Directory Traversal Attacks" not applicable.

Middlewares can be defined by use() or by dropping index.js files in the desired folders. These must export either a plain middleware function or an array of functions.

Functions

configure(object)

Provides the possibility to change the following defaults.

  • ext: string extension of middleware files e.g..ts; default: .js
  • entry: string name of middleware files e.g.middleware; default: index

on(method, path, handler)

Register custom handlers to specific paths.

  • method: string one of: *, get, post, put, patch, delete, head, options
  • path: string pathname to match
  • handler: Function callback function receiving req and res as parameters

use(middleware)

Register a middleware function.

  • middleware: Function e.g.(req, res, next) => next()

has(method, path)

Returns true of the requested route exists.

  • method: string one of: *, get, post, put, patch, delete, head, options
  • path: string pathname

chain(middlewares)

Transforms an array of middleware functions into a single middleware function.

  • middlewares: Array<Function> similar to use() but with arrays

register(basepath, onDone)

Recursively register the given path and its subfolders.

  • basepath: string path to folder
  • onDone: Function optional; called if registration done

route(req, res)

Handle the incoming requests.

  • req: IncomingMessage server request object
  • res: ServerResponse server response object

listener

listener Instance exposes three functions to bind, unbind and emit events.

Events

Following Events are available:

  • Ready if micro-r is done with register()
  • Error if an uncatched error in middleware, route or register call occurred

on(event, handler)

Register an event handler.

  • event: string name of the event
  • handler: function event handler

off(event, handler)

Unregister an event handler.

  • event: string name of the event
  • handler: function event handler

emit(event, req, res, payload)

Emit an event with payload.

  • event: string name of the event
  • req: IncomingMessage server request object
  • res: ServerResponse server response object
  • payload: any any kind of data

Example

Following folder/file structure with default configuration

routes
|
├───api
|       index.js
|       get.js
|
├───photo
|   |   index.js
│   │   get.js
│   │   post.js
│   │   delete.js
│   │
│   └───vacation
|           index.js
│           get.js
│           post.js
│
└───user
        post.js

registers the following routes

  • GET: example.com/api
  • GET: example.com/photo
  • POST: example.com/photo
  • DELETE: example.com/photo
  • GET: example.com/photo/vacation
  • POST: example.com/photo/vacation
  • POST: example.com/user

Vanilla

const {default: router, Event} = require('micro-r');
const {send} = require('micro');

const fallback = (req, res) => {
    send(res, '404', 'WOOPS');
};

const {on, use, chain, register, route, listener} = router(fallback);

listener.on(Event.READY, () => console.info('I\'m ready'));
listener.on(Event.ERROR, (req, res, error) => console.error(req, res, error));

register('./routes');

on('get', '/foo', async (req, res) => {
    send(res, 200);
});

const middlewares = [
    (req, res, next) => {
        res.data = [];
        next();
    },
    (req, res, next) => {
        res.data.push('foobar');
        next();
    },
];
 
on('get', '/custom', chain(middlewares)(async (req, res) => {
    // res.data === ['foobar']
    send(res, 200);
}));

module.exports = route;

Express

const {default: router, Event} = require('micro-r');
const express = require('express');

const app = express();

const fallback = (req, res) => {
    send(res, '404', 'WOOPS');
};

const {register, route, listener} = router(fallback);

register('./routes', () => console.info('I\'m ready'));

app.use(route);
app.listen(3000);

Licence

MIT License

Copyright (c) 2019 Oleg Kamlowski

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.