Request handlers is special classes used to handle and proceed single request. For each request new instance of RequestHandler class is instantiated.
Here the list of available HTTP methods decorators:
@GET, @HEAD, @PATCH, @POST, @PUT, @OPTIONS, @DELETE
There's also one special decorator for all methods: @ALL
- Decorators can't be mixed, and you can use only one decorator per class/method.
Decorators have same signature, which consist of two overloads:
First overload:
name | type | required | default | description |
---|---|---|---|---|
url | string |
no | / |
Route url which will be passed to Fastify |
options | RouteShorthandOptions |
no | {} |
Config for route which will be passed to Fastify |
Second overload:
name | type | required | default | description |
---|---|---|---|---|
url | RouteOptions |
no | {} |
Route url and config to be passed to Fastify |
Every handler should extend base RequestHandler
class:
import { GET, RequestHandler } from 'fastify-decorators';
@GET('/')
class MyRequestHandler extends RequestHandler {
async handler() {} // concrete implementation of abstract method in RequestHandler
}
There are also decorator which allows using Fastify Hooks:
import { GET, Hook } from 'fastify-decorators';
@GET('/')
export default class Handler extends RequestHandler {
public handle(): Promise<never> {
return Promise.reject({ code: 'NOT_IMPLEMENTED' });
}
@Hook('onSend')
async onSend(request, reply) {
reply.removeHeader('X-Powered-By');
}
}
fastify-decorators
provides abilities to handle error with @ErrorHandler
decorator.
Decorator 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 { FastifyReply, FastifyRequest } from 'fastify';
import { ErrorHandler, GET, RequestHandler } from 'fastify-decorators';
@GET('/handler-with-error')
export default class HandlerWithErrorHandler extends RequestHandler {
public handle(): Promise<never> {
return Promise.reject({ code: 'NOT_IMPLEMENTED' });
}
@ErrorHandler('NOT_IMPLEMENTED')
handleNotImplemented(error: Error, request: FastifyRequest, reply: FastifyReply): void {
reply.status(422).send({ message: 'Not implemented' });
}
}