Newly Paranoid Maintainers

    micro-pico-router

    1.0.2 • Public • Published

    Micro Pico Router

    Absolutely minimal, zero-dependency, Node or Micro router.

    It allows you to map specific method-endpoint combinations to specific handlers.

    Getting Started

    npm install --save micro-pico-router
    

    Node HTTP Server Usage

    const http = require('http')
    const router = require('micro-pico-router')
     
    const app = router()
     
    app.get('/', (req, res) => {
      res.statusCode = 200
      res.end('okay')
    })
     
    app.post('/submit', (req, res) => {
      res.statusCode = 200
      res.end()
    })
     
    // If you not define a default handler it will return status 404 by default
    app.default((req, res) => {
      res.statusCode = 404
      res.end('Not Found')
    })
     
    http.createServer(app).listen(3000)

    The previous example, is the same as doing this:

    const http = require('http')
    const { parse } = require('url')
     
    http.createServer((req, res) => {
      const { pathname } = parse(req.url)
     
      if (req.method === 'GET' && pathname === '/') {
        res.writeHead(200, { 'Content-Type': 'text/plain' })
        res.end('Hello!')
      } else if (req.method === 'POST' && pathname === '/submit') {
        res.writeHead(200, { 'Content-Type': 'text/plain' })
        res.end('Thank you for submitting')
      } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' })
        res.end('Not Found')
      }
    }).listen(3000)

    Micro Usage

    const app = require('micro-pico-router')()
     
    module.exports = app.get('/', (req, res) => 'Hello!')

    Micro with Async

    const sleep = require('then-sleep')
    const app = require('micro-pico-router')()
     
    module.exports = app.get('/', async (req, res) => {
      await sleep(500)
      return 'Ready!'
    })

    HTTP Methods

    The methods available on app[METHOD] are the ones listed by http.METHODS, but lowercased.

    You can also give them using the options:

    const router = require('micro-pico-router')
     
    const app = router({
      methods: ['GET', 'WEIRD']
    })
     
    app.weird('/', (req, res) => 'Some weird http method!')

    Tests

    npm run test
    

    License

    MIT

    Install

    npm i micro-pico-router

    DownloadsWeekly Downloads

    0

    Version

    1.0.2

    License

    MIT

    Last publish

    Collaborators

    • mjlescano