uRouter

What it does

This decorator marks a class as a router instance that holds routing and request handlers metadata.

How to use
@uRouter()
class App {

  @uMethod.get()
  sayHello(req: uRequest, res: uResponse): void {
    res.send('Hello world')
  }
}
Description

The uRouter decorator will define a class as a router instance thats holds routing metadata such as path matching and handlers and group them together.

You will be required to define at least 1 uRouter instance to be bootstrapped as your main entry point.

You can include other routers as children of other routers, nesting them as many times as required, similar to how you would use express.use(path, routerGroup) in express.

  • prefix <string> - Prefixes all handlers defined in this MicroRouter instance. Note: that this will also prefix all handlers that are children of this router

  • middleware <MiddlewareFunction[]> -

  • children <RouterChild[]> -

Examples

Router nesting
@uRouter({
  prefix: 'users'
})
class ChildRouter {
  @uMethod.get()
  getUsers(req: uRequest, res: uResponse): void {
    res.send(['John', 'Trevor'])
  }

  @uMethod.get('active')
  getUsers(req: uRequest, res: uResponse): void {
    res.send(['John'])
  }
}

@uRouter({
  children: [
    ChildRouter
  ]
})
class ParentRouter {
  @MicroMethod.get()
  sayHello(req: uRequest, res: uResponse): void {
    res.send('Hello World')
  }
}

uApp.bootstrap(ParentRouter, { port: 3000 })

http://localhost:3000 will return Hello World.

http://localhost:3000/users will return ['John', 'Trevor'].

http://localhost:3000/users/active will return ['John'].

Middleware

You can use existing express.js middlewares with microdose or create your own as described below.

Express Middleware

Note that the ordering is important, similar how you would do it in express.js.

import * as bodyParser from 'body-parser'

@uRouter({
  children: [ChildRouter],
  middleware: [
    bodyParser.json()
  ]
})
class ParentRouter {
...
}

Custom Middleware

Suppose we define a very basic middleware function that checks for a token in the request. Let's call the file middleware.ts.

export const secretMiddleware = (req: uRequest, res: uResponse, next: uFunction) => {

    const secret = req.headers['authorization']

    if (!secret) {
        res.send(401, 'missing_token')
        return
    }

    if (!/Bearer /.test(secret)) {
        res.send(400, 'token_malformed')
        return
    }

    const token = secret.replace('Bearer ', '')

    // imaginary validation
    const tokenValid = true

    if (!tokenValid) {
        res.send(401, 'invalid_token')
        return
    }

    next()

    // or you can overwrite the request to be passed on to the next handler
    // req.user = decodeToken(token).user
    // next(req)
}

Let's modify our router to incorporate the middleware function for all requests.

import { secretMiddleware } from './middleware'

@uRouter({
    children: [ChildRouter],
    middleware: [secretMiddleware]
})
class ParentRouter {
...
}

Check if it is working

$ curl -H "Authorization: Bearer myTopSecretToken" http://localhost:3000/foo
$ Hello World
$ curl -H "Authorization: Bear myTopSecretToken" http://localhost:3000/foo
$ token_malformed
$ curl http://localhost:3000/foo
$ missing_token

NOTE that when defining a middleware function inside the uRouter decorator, the middleware will be applied to all handlers of that route AND it's children. So in this case the url http://localhost:3000/foo/users will also be covered.

results matching ""

    No results matching ""