Skip to Content
HeronJS 3.6 with fully support Typescript 6 is released šŸŽ‰

REST controllers handle incoming HTTP requests and return responses to the client. In HeronJS, you define them with the @Rest() decorator and attach route handlers with method decorators such as @Get() and @Post().

Create a REST controller

Create a file for your controller, for example:

  • src/rests/todo.rest.ts
import { Rest } from '@heronjs/common'; @Rest('/todos') export class TodoRest {}

This creates a controller whose routes are grouped under /todos.

Define a route

Add route decorators inside the class to handle specific HTTP methods.

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

In this example, HeronJS exposes a GET /todos endpoint.

Use parameter decorators

Parameter decorators let you access request data directly in a route handler.

DecoratorDescriptionNote
@Header(name)Gets a header value by name.
@Params()Gets a route parameters.
@Body()Gets the request body.
@Queries()Gets all query parameters.
@Request()Gets the HttpRequest instance.
@Response()Gets the HttpResponse instance.Use this when you want to write the response manually.
@Principle(name)Gets the authenticated value from the GateKeeper context.
import { Body, Get, Param, Post, Query, Rest } from '@heronjs/common'; @Rest('/todos') export class TodoRest { @Get({ uri: '/:id' }) public async findOne( @Param('id') id: string, @Query('includeCompleted') includeCompleted?: string, ): Promise<any> { return { id, includeCompleted }; } @Post({ uri: '/' }) public async create(@Body() body: any): Promise<any> { return body; } }

Register REST routes

To enable the controller, register it in your module controllers array.

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

Once registered, HeronJS includes the controller when the application starts.

Supported route decorators

DecoratorDescription
@GetHandles GET requests.
@PostHandles POST requests.
@PutHandles PUT requests.
@PatchHandles PATCH requests.
@DeleteHandles DELETE requests.

Each route decorator accepts an options object with these common properties:

  • uri defines the route path.
  • code sets the response status code. The default is usually 200.
  • headers defines response headers.
@Get({ uri: '/health', code: 204, headers: { 'content-type': 'application/json', }, })
Last updated on