Decorators

Controller Decorators Overview

createDecorator is a higher-order function that produces a decorator factory (a function that returns a decorator) for Controller Class methods. It accepts a middleware function with the following parameters:

  • request, which extends NextRequest as well as VovkRequest.
  • next, a function that should be invoked and its result returned to call subsequent decorators or the route handler.
  • Additional arguments are passed through to the decorator factory.

The second argument of createDecorator is an optional init handler. It's called every time when decorator is initialised and it's used to populate .vovk.json with information on client-side validation described at Validation docs.

import { createDecorator, get, HttpException, HttpStatus } from 'vovk';
 
const myDecorator = createDecorator((req, next, a: string, b: number) => {
  console.log(a, b); // Outputs: "foo", 1
 
  if(isSomething) { 
    // override route method behavior and return { hello: 'world' } from the endpoint
    return { hello: 'world' };
  }
 
  if(isSomethingElse) {
    // throw HTTP error if needed
    throw new HttpException(HttpStatus.BAD_REQUEST, 'Something went wrong');
  }
 
  return next();
}, (a: string, b: number) => {
    console.info('Decorator is initialised with', a, b);
});
 
class MyController {
  @get.auto()
  @myDecorator('foo', 1) // Passes 'foo' as 'a', and 1 as 'b'
  static doSomething() {
    // ...
  }
}