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

obj-router

v3.0.2

Published

A lightweight router based on objects for NodeJS Promises. For small web services.

Downloads

133

Readme

obj-router

A lightweight router based on objects for NodeJS Promises. For small web services.

Note

This update contains the following breaking changes from version 2.x.x:

  • HttpError.code is now HttpError.status
  • HttpError.msg is now removed, use HttpError.message instead
  • router.execute() now returns a TypeError instead of an HttpError if an endpoint is not a function

Example

const routes = require('hello.routes')
const router = new Router(routes)

const req = {
	surname: 'Appleseed'
}
const message = await router.execute('/hello/mr?name=John', req)
// `message` = 'Hello mr. John Appleseed!'

hello.routes.js

module.exports = {
    '/hello': {
        ':title': {
            get: req => {
              return Promise.resolve(`Hello ${req.params.title}. ${req.query.name} ${req.surname}!`)
            }
        }
    }
}

API

Routing

/path

Regular paths are marked with /.

:param

Parameters starts with : and can be accessed in req.params

* (Wildcard)

Catches all requests.
Can be a subpath but can only have direct children that are methods.

method

Each endpoint should be a key-value pair of a method name and a function returning the desired value wrapped in a promise. The resolver comes pre-loaded with standard HTTP-methods but can be expanded with the use of custom resolvers.

The following methods will be resolved:

get
head
post
put
delete
patch

new Router(routes)

.execute(path, req?, ...args?)

Execute a path, returns a promise

.resolve(path, req?)

Resolve a path, returns null or a value

.routes

The routes object passed to the constructor


req

The req object is used throughout the router and acts as a payload for the endpoint being executed. It can be accessed and modified by any resolvers along the way.

{
  method: String // any of ['get', 'head', 'post', 'put', 'delete', 'patch'], defaults to 'get'

  // The following keys are read-only
  path: [String] // an array of keys representing the path being resolved
  pathname: String // the path being resolved as a string
  query: {} // a key-value object containing any query parameters
  params: {} // a key-value object containing any path parameters
}

Resolvers

Resolvers are always executed synchronously in order until an object is returned, representing the next routing level. Returning an object will prevent the following resolvers to be executed on that level.

A resolver should have the following signature:

function resolver (obj, path, opts, resolve)  {
  // `obj` is the object to be resolved
  // `path` represents the path to resolve as an array of strings, path[0] is the key currently being resolved
  // `resolve` is a callback function that takes the resolved object as its first argument, a path as its second and options as its third. If this function isn't called the next resolver will be called with the same arguments.
  // `opts` contains payload data for the operation. opts.req represents the request object.

  // Must call resolve with at least its first argument
  // if route is to be resolved by this resolver
  // resolve(obj, path, opts)
}

.addResolverBefore(resolver)

Prepends a resolver to the stack of resolvers

.addResolverAfter(resolver)

Appends a resolver to the stack of resolvers


Errors

Errors connected to an HTTP status code are encapsulated in the HttpError class.

const HttpError = require('obj-router').HttpError

const notFound = new HttpError(404)
// notFound.status = 404
// notFound.message = 'Not Found'

new HttpError(status [,message])

Create a new HttpError.

.status

A public property containing the HTTP status code representing the error.

.message

A public property containing a message describing the error. If no message was provided to the constructor a default one will be set based on the status code.

HttpError.status

A static gettable property returning an object with all available status codes,

License