jeffijoe / awilix-express

Awilix helpers/middleware for Express
MIT License
118 stars 7 forks source link

param decorator #21

Closed sykire closed 5 years ago

sykire commented 5 years ago

Not a real issue. Untested but should work. This is a method decorator to put inside your controller, that registers a method as a before middleware that will execute everytime a certain param is present

import { makeInvoker, before } from "awilix-express"

/**
 * Adds a root-level before-middleware that will only be executed if
 * exists a param with the name passed to the function
 */
export function param(paramName:string){
    return function routerDecorator(target : any, name : string ){
        let invoker = makeInvoker(target.constructor)(name)
        function paramMiddleware(req, res, next){
            let param = req.params[paramName]
            param != null ?
                invoker(req, res, next) :
                next()
        }
        before(paramMiddleware)(target)
    }
}

Usage:

class PostController {
  postService : PostService
  constructor({ postService }){
     this.postService = postService
  }

  @param('postId')
   async loadPost(req, res, next) {
      let postId = req.params.postId
      let post = await this.postService.get(postId)
      if(!post){
        throw new NotFoundError()
      }
      req['post'] = post
      next()
   }

  @route('/:postId')
  @GET()
  async getPost(req, res){
    let post : Post = req['post'] // <- should be present otherwise the `loadPost` method would have thrown
    res.json(post)
  }
}

I leave it here in case it is useful for someone