backend/src/middlewares/graphql-logger.ts (view raw)
1import chalk from "chalk";
2
3export default (_, { strapi }) => {
4 return async (ctx, next) => {
5 const start = Date.now();
6 await next();
7 const delta = Math.ceil(Date.now() - start);
8
9 if (ctx.url === "/graphql") {
10 const user = ctx.state?.user?.username;
11 const { operationName = "", variables, query } = ctx.request.body || {};
12 const status = graphqlStatus(ctx.body);
13
14 strapi.log.http(
15 `${chalk.magenta(
16 "GRAPHQL"
17 )} ${operationName} (${delta} ms) ${graphqlCodeColor(status)}`,
18 {
19 meta: {
20 operationName,
21 variables,
22 query,
23 status,
24 delta,
25 user,
26 },
27 }
28 );
29 } else {
30 strapi.log.http(
31 `${ctx.method} ${ctx.url} (${delta} ms) ${httpCodeColor(ctx.status)}`
32 );
33 }
34 };
35};
36
37const graphqlStatus = (response) => {
38 if (!response) return "NOT FOUND";
39
40 try {
41 const { errors = null } = response ? JSON.parse(response) : {};
42 if (errors) return "ERROR";
43 } catch (error) {
44 console.error(error);
45 return "ERROR";
46 }
47
48 return "OK";
49};
50
51const graphqlCodeColor = (status) => {
52 switch (status) {
53 case "ERROR":
54 return chalk.red(status);
55 case "NOT_FOUND":
56 return chalk.yellow(status);
57 default:
58 return chalk.green(status);
59 }
60};
61
62const httpCodeColor = (code) => {
63 return code >= 500
64 ? chalk.red(code)
65 : code >= 400
66 ? chalk.yellow(code)
67 : code >= 300
68 ? chalk.cyan(code)
69 : code >= 200
70 ? chalk.green(code)
71 : code;
72};