@athenna/http
Version:
The Athenna Http server. Built on top of fastify.
111 lines (110 loc) • 3.39 kB
JavaScript
/**
* @athenna/http
*
* (c) João Lenon <lenon@athenna.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { Is } from '@athenna/common';
import { Request } from '#src/context/Request';
import { Response } from '#src/context/Response';
import { NotFoundException } from '#src/exceptions/NotFoundException';
export class FastifyHandler {
/**
* Parse the fastify request handler and the preHandler hook to an Athenna
* request handler.
*/
static request(handler) {
return async (req, res) => {
if (!req.data) {
req.data = {};
}
const ctx = {};
ctx.data = req.data;
ctx.request = new Request(req);
ctx.response = new Response(res, ctx.request);
await handler(ctx);
};
}
/**
* Just and alises for the request handler.
*/
static handle(handler) {
return this.request(handler);
}
/**
* Parse the fastify onSend hook to an Athenna intercept handler.
*/
static intercept(handler) {
return async (req, res, payload) => {
if (!req.data) {
req.data = {};
}
if (Is.Json(payload)) {
payload = JSON.parse(payload);
}
res.body = payload;
const ctx = {};
ctx.data = req.data;
ctx.request = new Request(req);
ctx.response = new Response(res, ctx.request);
ctx.status = ctx.response.statusCode;
payload = await handler(ctx);
req.body = payload;
if (Is.Object(payload)) {
payload = JSON.stringify(payload);
}
return payload;
};
}
/**
* Parse the fastify onResponse hook to an Athenna terminate handler.
*/
static terminate(handler) {
return async (req, res) => {
if (!req.data) {
req.data = {};
}
const ctx = {};
ctx.data = req.data;
ctx.request = new Request(req);
ctx.response = new Response(res, ctx.request);
ctx.status = ctx.response.statusCode;
ctx.responseTime = ctx.response.elapsedTime;
await handler(ctx);
};
}
/**
* Parse the fastify onError hook to an Athenna error handler.
*/
static error(handler) {
return async (error, req, res) => {
if (!req.data) {
req.data = {};
}
const ctx = {};
ctx.data = req.data;
ctx.request = new Request(req);
ctx.response = new Response(res, ctx.request);
ctx.error = error;
await handler(ctx);
};
}
/**
* Parse the fastify not found route handler.
*/
static notFoundError(handler) {
return async (req, res) => {
if (!req.data) {
req.data = {};
}
const ctx = {};
ctx.data = req.data;
ctx.request = new Request(req);
ctx.response = new Response(res, ctx.request);
ctx.error = new NotFoundException(`Route ${req.method}:${req.url} not found`);
await handler(ctx);
};
}
}