Options
All
  • Public
  • Public/Protected
  • All
Menu

Class HTTPRouter<T, U>

A router specifically meant for use with HTTP servers

import * as http from 'http';
import { HTTPRouter, URLReq } from 'zephyri';

// IncomingMessage does not always have url or method
type Request = http.IncomingMessage & URLReq
type Response = http.ServerResponse

const router = new HTTPRouter<Request, Response>()
 .on('GET', '/:param', (req, res, params) => res.end(JSON.stringify(params)))
 .on('GET', '/user/:id', (req, res, params) => res.end(params.id))
 .on('GET', '**', (req, res) => res.end('404'));

// We cast req as Request because we know `url` and `method` is on `http.Server` incoming requests
http
 .createServer((req, res) => router.lookup(req as Request, res))
 .listen(3000)

Type parameters

Hierarchy

  • HTTPRouter

Index

Properties

Methods

Properties

router

router: Router<[T, U]> = new Router<[T,U]>()

The base router

Methods

lookup

  • lookup(req: T, res: U): void
  • Lookup a path and see if one exists, if it exists then the corresponding handler to the match will be called

    router.lookup('/user/1')

    Parameters

    • req: T
    • res: U

    Returns void

on

  • Add a listener with a handler that will be called if a lookup match is found

    router.on('GET', '/user/:id', (req, res, params) => {
      res.end(JSON.stringify(params.id))
    })

    Parameters

    Returns this

Generated using TypeDoc