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.
| Decorator | Description | Note |
|---|---|---|
@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
| Decorator | Description |
|---|---|
@Get | Handles GET requests. |
@Post | Handles POST requests. |
@Put | Handles PUT requests. |
@Patch | Handles PATCH requests. |
@Delete | Handles DELETE requests. |
Each route decorator accepts an options object with these common properties:
uridefines the route path.codesets the response status code. The default is usually200.headersdefines response headers.
@Get({
uri: '/health',
code: 204,
headers: {
'content-type': 'application/json',
},
})