-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (57 loc) · 1.43 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const fp = require("fastify-plugin");
const COLORS = {
yellow: 33,
green: 32,
blue: 34,
red: 31,
grey: 90,
magenta: 35,
clear: 39,
};
const colorText = (color, string) =>
`\u001b[${color}m${string}\u001b[${COLORS.clear}m`;
function colorMethod(method) {
switch (method) {
case "POST":
return colorText(COLORS.yellow, method);
case "GET":
return colorText(COLORS.green, method);
case "PUT":
return colorText(COLORS.blue, method);
case "DELETE":
return colorText(COLORS.red, method);
case "PATCH":
return colorText(COLORS.grey, method);
default:
return method;
}
}
function printRoutes(routeOptions, opts) {
const { colors } = opts;
if (routeOptions.length === 0) {
return;
}
//Sort route Options
routeOptions.sort((a, b) => a.url.localeCompare(b.url));
console.info("Available routes:");
for (const routeOption of routeOptions) {
const { method, url } = routeOption;
if (method === "HEAD") continue;
console.info(`${colors ? colorMethod(method) : method}\t${url}`);
}
}
function fastifyListRoute(instance, opts, next) {
const routeOptions = [];
instance.addHook("onRoute", (routeOption) => {
routeOptions.push(routeOption);
});
instance.addHook("onReady", (done) => {
printRoutes(routeOptions, opts);
done();
});
next();
}
module.exports = fp(fastifyListRoute, {
name: "fastify-list-routes",
fastify: "5.x",
});