MicroRouter

What it does

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

How to use
@MicroRouter()
class AppRouter {

    @MicroMethod.Get()
    sayHello(req: MicroRequest, res: MicroResponse): void {
        res.send('Hello world')
    }
}
Description

The MicroRouter 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 MicroRouter 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
@MicroRouter()
class SubRoutes {
    @MicroMethod.Get()
    getUsers(req: MicroRequest, res: MicroResponse): void {
        res.send(['John', 'Trevor'])
    }
}

@MicroRouter({
    children: [{prefix: '/users', router: SubRoutes}]
})
class MainRoutes {
    @MicroMethod.Get()
    sayHello(req: MicroRequest, res: MicroResponse): void {
        res.send('Hello World')
    }
}

MicroBootstrap(MainRoutes)

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

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

Prefix

If we modify the configuration for MicroRouter on MainRoutes to:

@MicroRouter({
    prefix: '/foo',
    children: [{prefix: '/users', router: SubRoutes}]
})

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

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

NOTE how all handlers defined as children of MainRoutes all also prefixed.

Middleware

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

export const secretMiddleware = (req: MicroRequest, res: MicroResponse, next: NextFunction) => {

    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'

@MicroRouter({
    prefix: '/foo',
    children: [{prefix: '/users', router: SubRoutes}],
    middleware: [secretMiddleware]
})

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 MicroRouter 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 ""