45 lines
1.4 KiB
TypeScript
45 lines
1.4 KiB
TypeScript
import fastifyPlugin from "fastify-plugin";
|
|
|
|
import type { FastifyError, FastifyInstance, FastifyPluginOptions, RouteOptions } from "fastify";
|
|
|
|
type PrintRoutesRouteOptions = {
|
|
hide?: boolean;
|
|
};
|
|
|
|
const METHODS_ORDER = ["GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS"];
|
|
|
|
const printRoutes = (routes: Array<RouteOptions & PrintRoutesRouteOptions> = [], isSwagger = false) => {
|
|
if (routes.length === 0) {
|
|
return;
|
|
}
|
|
|
|
const filteredRoutes = routes.filter((route) => route.hide !== true);
|
|
const sortedRoutes = [...filteredRoutes].sort((routeA, routeB) => routeA.url.localeCompare(routeB.url));
|
|
const output = sortedRoutes.reduce<string>((accamulator, route) => {
|
|
const methods = Array.isArray(route.method) ? route.method : [route.method];
|
|
const methodsValue = [...methods].sort((a, b) => METHODS_ORDER.indexOf(a) - METHODS_ORDER.indexOf(b)).join(" | ");
|
|
|
|
return accamulator + `${methodsValue}\t${route.url}\n`;
|
|
}, "");
|
|
const swaggerOutput = isSwagger ? "GET\t/swagger\n" : "";
|
|
|
|
console.info(`\n\nAvailable routes:\n${output + swaggerOutput}`);
|
|
};
|
|
|
|
export default fastifyPlugin(
|
|
(instance: FastifyInstance, _: FastifyPluginOptions, done: (error?: FastifyError) => void) => {
|
|
const routes: Array<RouteOptions> = [];
|
|
|
|
instance.addHook("onRoute", (route) => {
|
|
routes.push(route);
|
|
});
|
|
|
|
instance.addHook("onReady", (next) => {
|
|
printRoutes(routes, !!instance.swagger);
|
|
next();
|
|
});
|
|
|
|
done();
|
|
}
|
|
);
|