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-api-router

v1.1.0

Published

Micro middleware to standardise API microservices

Downloads

7

Readme

Micro API Router

CircleCI XO code style Prettier code style Greenkeeper badge NPM badge

Summary

Micro API Router helps to standardise API microservices. It's middleware for ZEIT's Micro and provides a level of base functionality out of the box such as:

  • CORS headers
  • Correlation ID header (X-Correlation-ID provided by micro-correlation-id)
  • Health Check endpoint (/health)
  • JSON error handling
  • Request logging

Installation

npm install --save micro-api-router

Or even better

yarn add micro-api-router

Usage

Basic

const { createRouter } = require('micro-api-router')
const request = require('some-request-lib')
const handler = () => 'ok!'

// service.js
module.exports = createRouter().get('/', handler)

// test.js
const response = await request('/')
console.log(response) // 'ok!'

API

createRouter([options])

Creates a new router. Adds a default /health endpoint which will return all information under options.application. Returns an object with the following route methods (each method returns the router object to allow chaining):

  • get(path = String, handler = Function)
  • post(path = String, handler = Function)
  • put(path = String, handler = Function)
  • patch(path = String, handler = Function)
  • del(path = String, handler = Function)
  • head(path = String, handler = Function)
  • options(path = String, handler = Function)
path

The URL pattern to define your path. Parameters are specified using : notation and they, along with query parameters, will be returned as part of the req object passed to handler.

For more information about defining paths, see url-pattern. This package is used to match paths.

handler

A simple function that will make some action based on your path. The format of this function is (req, res) => {}

req.params

As shown below, the parameters specified in the path will be present as part of the req parameter:

const { createRouter } = require('micro-api-router')
const request = require('some-request-lib')

// service.js
module.exports = createRouter().get('/hello/:who', (req, res) => req.params)

// test.js
const response = await request('/hello/World')
console.log(response)  // { who: 'World' }
req.query

As shown below, the query parameters used in the request will also be present as part of the req parameter:

const { createRouter } = require('micro-api-router')
const request = require('some-request-lib')

// service.js
module.exports = createRouter().get('/hello', (req, res) => req.query)

// test.js
const response = await request('/hello?who=World')
console.log(response)  // { who: 'World' }
Options

Defaults:

{
  application: {                                    // Application-specific properties. Returned via `/health`
    name: process.env.API_NAME || 'Unknown',        // Name of the micro service
    description: process.env.API_DESCRIPTION || '', // Desceription of the micro service
    host: process.env.API_HOST || 'unknown',        // Host url/name of the micro service
    dependencies: [],                               // Dependencies that the micro service relies on
    version: process.env.API_VERSION || 'N/A',      // Version of the micro service
  },
  cors: {
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowHeaders: [
      'Accept',
      'Authorization',
      'Access-Control-Allow-Origin',
      'Content-Type',
      'X-Correlation-ID',
      'X-HTTP-Method-Override',
      'X-Requested-With',
    ],
    exposeHeaders: [],
    maxAge: 86400,
    origin: '*',
  },
}

Example:

const { createRouter } = require('micro-api-router')
const request = require('some-request-lib')

// service.js
module.exports = createRouter({ application: { name: 'Micro API' } })

// test.js
const response = await request('/health')
console.log(response) // { name: 'Micro API', description: '' host: 'unknown', dependencies: [], version: 'N/A' }

createError(statusCode, message[, data])

Creates a Boom Error instance with the supplied statusCode, message and data. Use with throw to return an error.

Returned errors include the request's correlation ID.

const { createRouter, createError } = require('micro-api-router')
const request = require('some-request-lib')

const error = () => throw createError(500, 'Internal Server Error')
const errorWithData = () => throw createError(500, 'Internal Server Error', { some: 'data' })

// service.js
module.exports = createRouter()
  .get('/error', error)
  .get('/errorWithData', errorWithData)

// test.js
let response = await request('/error')
console.log(response) // { statusCode: 500, error: 'Internal Server Error', message: 'An internal server error occurred', correlationId: '123' }

response = await request('/errorWithData')
console.log(response) // { statusCode: 500, error: 'Internal Server Error', message: 'An internal server error occurred', correlationId: '123', data: { some: 'data' } }

getId()

Returns the correlation ID of the current request. Must be used inside a handler function.

The current correlation ID is either a generated UUIDv4 or the value passed in via the request's x-correlation-id header.

log

The log object used in Micro API Router. By default, all logs are output to the console in JSON format. For more information on customising the logging or adding new loggers, see: Bristol.

All logs output using this logger will automatically include the Correlation ID assigned to each request. Micro API Router also logs all incoming requests to the console by default.

Contributing

  1. Fork this repository to your own GitHub account and then clone it to your local device
  2. Install the dependencies with yarn install
  3. Create a pull request with your changes when ready

You can run the Jest test by using yarn test and the XO metrics by using: yarn metrics

Inspired By

License

MIT © James Carr