Function: fastifyHTTPEntrypoint()
fastifyHTTPEntrypoint(
options?):EntrypointAdapter<HTTPContext<{ }>>
Create the HTTP adapter of an entrypoint served by a fastify instance: each HTTP action (@GET, @POST, @HTTPAction…) becomes a fastify route. It needs the optional peer dependency fastify.
An action's input is the request's query and body (see the input option) with the route parameters merged over them. Its result is written by the responder (JSON by default, 204 for no result); a StatusResult sets the status and the headers, a FileResult sends a file, a buffer or a stream (its content type guessed from the extension of its file name, 304 when its ETag matches If-None-Match), and an EventsResult streams Server-Sent Events. An action that writes the response itself (through HTTPContext.response) is left alone. The errors, those of fastify included (a body too large: 413, a malformed JSON body: 400), are written by the responder with their status (500 by default). A GET action also answers HEAD, unless a HEAD action is declared for its route.
When the client disconnects before the response, the action's abort signal fires and nothing is written. When the entrypoint stops, fastify stops accepting connections and answers the new requests with 503, the event streams end, and the requests in progress are given up to one second after they settle to send their responses before the remaining connections are closed — the connections taken over by an upgrade (the WebSockets of the application) too, which would hold the stop forever.
Parameters
options?
The adapter options; by default it listens on port 80 with a new fastify instance.
Returns
EntrypointAdapter<HTTPContext<{ }>>
The adapter, to give to the http option of buildEntrypoints.
Example
import {Application} from 'lakutata'
import {buildEntrypoints, Controller} from 'lakutata/com/entrypoint'
import {GET, POST} from 'lakutata/decorator/ctrl'
import {fastifyHTTPEntrypoint} from 'lakutata/adapter/fastify'
class UserController extends Controller {
//GET /users/1?verbose=true: the route parameter id merged over the query
@GET('/users/:id')
public async get(input: {id: string, verbose?: string}): Promise<{id: string}> {
return {id: input.id}
}
//POST /users with the JSON body {"name": "Ada"}
@POST('/users')
public async create(input: {name: string}): Promise<{name: string}> {
return {name: input.name}
}
}
Application.run({
id: 'web.app',
name: 'Web',
components: {
entrypoint: buildEntrypoints({
controllers: [UserController],
http: fastifyHTTPEntrypoint({
port: 8080,
host: '0.0.0.0',
fastify: {bodyLimit: 5 * 1024 * 1024, trustProxy: true},
//The application's own routes
before: (app): void => {
app.get('/health', async (): Promise<string> => 'ok')
}
})
})
},
bootstrap: ['entrypoint']
})