Controller is class decorated with @Controller
and designed to handle request to its routes.
First step is to create a class and decorate it
import { Controller } from 'fastify-decorators';
@Controller()
export default class SimpleController {}
Controller decorator configuration:
Controller decorator may accept 2 kinds of options
-
String which represent route URL which will be the root path of our controller's endpoints.
default is
'/'
-
Object which contains
route
representing URL used as the root path andtype
for controller type.Controller must be one of the two types:
ControllerType.SINGLETON
- creates single class instance for all requestsControllerType.REQUEST
- creates new class instance per request
Controller is able to handle different HTTP requests methods with different routes. For that, we need to declare a controller class method and decorate it with HTTP method decorator.
List of available decorators: GET
, POST
, PUT
, PATCH
, DELETE
, 'HEAD' and OPTIONS
.
There also special decorator in place - ALL
which will handle all types of request.
import { FastifyRequest, FastifyReply } from 'fastify';
import { Controller, GET } from 'fastify-decorators';
@Controller()
export default class SimpleController {
@GET()
async getHandler(request: FastifyRequest, reply: FastifyReply) {
return 'Hello world!';
}
@POST()
async postHandler(request: FastifyRequest, reply: FastifyReply) {
// Doing some activities here
}
}
Read Request Handlers for more info.
There are also decorator which allows using Fastify Hooks:
import { Controller, Hook } from 'fastify-decorators';
@Controller('/')
export default class SimpleController {
@Hook('onSend')
async onSend(request, reply) {
reply.removeHeader('X-Powered-By');
}
}
fastify-decorators
provides abilities to handle error with @ErrorHandler
decorator.
@ErrorHandler
may accept error code or type to handle or be empty which means will handle all errors. Let's take a look on example:
import fs from 'node:fs';
import path from 'node:path';
import { Controller, GET, ErrorHandler } from 'fastify-decorators';
class TokenNotFoundError extends Error {}
@Controller('/')
export default class SimpleController {
@GET('/')
async get(request, reply) {
// may throw FS_READ_ERROR
const content = fs.readFileSync(path.join(__dirname, request.query.fileName));
if (!content.includes('token')) {
throw new TokenNotFoundError('Token not found in file requested');
}
return { message: 'ok' };
}
@ErrorHandler(TokenNotFoundError)
handleTokenNotFound(error: TokenNotFoundError, request, reply) {
reply.status(403).send({ message: 'You have no access' });
}
}