Overview
Rest

Rest are responsible for handling incoming requests and returning responses to the client requests.

Create a file to src/controllers to create a a rest controller:

  • src/rests/todos.rest.ts

Create a Rest

import { Rest } from '@heronjs/common';
 
@Rest('/todos')
export class TodoRest {}

A new resource is now available at http://localhost:3000/todos.

Define a Route

Let's assume you need to create a GET method api that get all todos.

import { Rest } from '@heronjs/common';
 
@Rest('/todos')
export class TodoRest {
 
    @Get({ uri: '/'})
    public async findAll(): Promise<TodoModel> {
        return ['todo1'];
    }
}

A new api route is now available at http://localhost:3000/todos with GET method.

Parameter Decorators

DecoratorDescriptionNote
@Header(name)Get header value by name
@Param(name)Get param value by name
@Body()Get body of request
@Query(name)Get a query parameter of request
@Queries()Get all query parameters of request
@Request()Get HttpRequest class
@Response()Get HttpResponse classUse this decorator when you need to handle the response manually.
@Principle(name)Get Auth valueGatekeeper Auth Value
@Rest('/todos')
export class TodoRest {

    @Get({ uri: '/'})
    public async findAll(): Promise<TodoModel> {
        return ['todo1'];
    }
}

Register Rest Routes

Add TodoRest class to @Module({}) controller property to enable the routes

@Module({
    controllers: [TodoRest],
})
export class AppModule {}

Supported Decorators

DecoratorDescription
@GetGet Method
@PostPost Method
@PutPut Method
@PatchPatch Method
@DeleteDelete Method

The decorators has 3 arguments uri , code and headers

  • uri - the uri of the request
  • code - the response code (it's 200 by default)
  • headers - accept the object of headers
 @Get({
     uri: '/api',
     code:204,
     headers:{'content-type':'application/xml'}
     // headers:{'content-type': ()=> Date.now()} a header value can be a function
 })