Skip to content

Variable: buildHTTPEntrypoint ​

const buildHTTPEntrypoint: (entrypoint) => HTTPEntrypoint

Type an HTTP entrypoint in the style of lakutata 2.x; the function is returned as it is.

Parameters ​

entrypoint ​

HTTPEntrypoint

The function the entrypoint calls when it starts, with the module, the routes, the request handler and the destroyer registrar.

Returns ​

HTTPEntrypoint

The same function, to give to the http option of buildEntrypoints.

Example ​

typescript
import {createServer, type Server} from 'node:http'
import {Application} from 'lakutata'
import {buildEntrypoints, buildHTTPEntrypoint, Controller, HTTPContext} from 'lakutata/com/entrypoint'
import {GET} from 'lakutata/decorator/ctrl'

class HealthController extends Controller {
    @GET('/health')
    public async health(): Promise<{status: string}> {
        return {status: 'ok'}
    }
}

Application.run(() => ({
    id: 'api.app',
    name: 'API',
    components: {
        entrypoint: buildEntrypoints({
            controllers: [HealthController],
            http: buildHTTPEntrypoint((module, routeMap, handler, registerDestroy): void => {
                const server: Server = createServer(async (request, response): Promise<void> => {
                    //The route map holds the routes and the methods as declared: '/health', 'get'
                    const route: string = (request.url ?? '/').split('?')[0]
                    const method: string = (request.method ?? 'GET').toLowerCase()
                    if (!routeMap.get(route)?.has(method)) {
                        response.writeHead(404).end()
                        return
                    }
                    const abortController: AbortController = new AbortController()
                    response.on('close', (): void => abortController.abort())
                    try {
                        const context: HTTPContext = new HTTPContext({route, method, request, response, data: {}})
                        response.end(JSON.stringify(await handler(context, abortController)))
                    } catch (error) {
                        response.writeHead(500).end((error as Error).message)
                    }
                }).listen(3000)
                registerDestroy((): Promise<void> => new Promise((resolve): void => void server.close((): void => resolve())))
            })
        })
    },
    bootstrap: ['entrypoint']
}))

Released under the MIT License.