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

abstract-express-router

v1.6.0

Published

library to automagically create an express router-object with basic validation for params based on a javascript object

Downloads

5

Readme

abstract-express-router

codecov CircleCI npm

An framework for express.js which abstracts much of the syntax needed for creating an express-router while keeping the core-functionality. This allows for a quick and clean creation of routers in a single file without writing repetitive code. It also provides simple validation functionality for path and query parameters and for the body.

Installation

npm install abstract-express-router

Also make sure that you have Node.js 10 or newer in order to use it.

Documentation

The main functionality is the creation of a router. For this it is necessary to create a Javascript object reflecting the structure of your api via string - object - pairs. Certain key names are restricted as they refer to specific functionality, but every other key will resolve into a seperate router instance with anything placed into the object mapped to its key value. It is possible to have multiple url-segments in a single key and it is also possible to use path parameters (e.g. "objects/:id").

Reserved Keys

The reserved keys are the following:

Action verbs: get, post, put, delete

Using an action verb will cause the creation of an endpoint. Each endpoint has the required key controller and allows for middleware and body, query, params

Controller

Controllers are required keys for every endpoint. They have to be a function and to terminate the request.

Middleware

Middleware is defined as an array of functions. They can be added in any layer.

Static

Static is a shorthand for express static routing and requires the source path for the static files as value. This keyword can be used in any layer except endpoints.

Validation

body, query and params allow for verification. body and query are restricted to endpoints, but params can be used on any layer. Validation can be done either by using one of the provided validators, or by passing a evaluation function which returns a boolean. It is possible to have multiple layers of objects for the validation. A failed validation for params will cause express to skip to the next router, while a failed validation for query and body terminates the request with error code 400.

Validators

This library provides some convenience functions for triggering the validation:

regexpValidator

This Validator will evaluate the value against the provided regular expression. const number = regexpValidator(/^[a-z]{0,25}$/)

oneOfValidator

This Validator will evaluate whether the value is part of the provided list. const repository = oneOfValidator(['test', 'foo'])

Order of application

  1. Validation
  2. Middleware
  3. Action Verbs
  4. Subrouters
  5. Static
  6. CatchAll

Configuration (optional)

logger

It is possible to pass a function in the configuration object. If this is done any logging will be passed into this function, split into the loglevel and the message:

{
	level: number
	message: string
}

logLevel

If no logger function is configured, all logging will be prefixed with the application name, filtered by log level and the output send to console.log. This library supports 4 log levels: 0 - silent, 1 - error, 2 - warning, 3 - info default: 3

useCatchAll

Whether to use the default catchAll returning a 404 error. default: true

bodyParserOptions

Configuration object to be passed into the json/urlEncoded bodyparser.

Example

import {createRouter, oneOfValidator, regexpValidator } from 'abstract-express-router'
import { createServer } from 'http'

const testMiddleware = testMiddleware2 = testMiddleware3 = (req, res, next) => {
	// do whatever
 	next()
}

// different types of validators
const number = regexpValidator(/^[a-z]{0,25}$/)
const repository = oneOfValidator(['test', 'foo'])
const id = regexpValidator(/^[0-9]{0,10}$/)
const report = (value) => value === 'report'

// handler
const handler1 = handler2 = (req, res) => res.status(200).send('hello')

const api = {
	middleware: [testMiddleware],
	api: {
		endpoint1: {
			middleware: [testMiddleware2],
			post: {
				body: { branch, report, repository },
				controller: handler1,
			},
		},
		endpoint2: {
			':id': {
				params: { id },
				put: {
					middleware: [testMiddleware3],
					body: {
						report,
						base: branch,
						repository,
					},
					controller: handler2,
				},
			},
		},
	},
	static: './path/of/static/content/'
}

const settings = {
	logger,
	logLevel: 2,
	useCatchAll: false
}

const app = createRouter(api, settings)
app.use(*, (req, res) => res.status(404).send('No luck here, try elsewhere!))

const server = createServer(app)

server.listen(8080)

Changelog

10.04.2019: added static router

License

ISC License