uMiddleware

The uMiddleware decorator allows you to wrap a handler inside a middleware. If you need a router-wider middleware, use the middleware parameter in uRouter. You may use existing express.js middlewares such as body-parser, cookie-parse etc.

You can define one like so, similar to express.

Handler Scoped Middleware

The below example shows how to define a middleware for a single request handler. The middleware function secretMiddleware is effective for the url /secret-data only.

*secret-middleware.ts*

...


const secretMiddleware = (req: uRequest, res: uResponse, 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)
}

*app.ts*

...
import { secretMiddleware } from './secret-middleware.ts'
import * as bodyParser from 'body-parser'

import {
  ...,
  uMiddleware
} from 'microdose'

@uRouter()
class MyApp {

  @uMethod.get('/secret-data')
  @uMiddleware(secretMiddleware)
  showSecret(req: uRequest, res: uResponse): void {
    res.send('you shall pass')
  }

  // Example with body-parser
  @uMethod.get('/public-data')
  @uMiddleware(bodyParser.json())
  showSecret(req: uRequest, res: uResponse): void {
    res.send('nothing confidential here')
  }
}

Test it

$ curl -H "Authorization: Bearer myTopSecretToken" http://localhost:3000/secret-data
$ you shall pass
$ curl -H "Authorization: Bear myTopSecretToken" http://localhost:3000/secret-data
$ token_malformed
$ curl http://localhost:3000/secret-data
$ missing_token

Router Scoped Middleware

See uRouter

results matching ""

    No results matching ""