This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
overtime.ts
173 lines (152 loc) · 5.34 KB
/
overtime.ts
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import axios from 'axios';
import { ChartData } from 'chart.js';
import type { NextApiRequest, NextApiResponse } from 'next';
import { withSessionRoute } from '@lib/AuthSession';
import { chartThemeColours } from '@utils/darkTheme';
import logger from '@utils/logger';
import { UpstreamApiUrl } from '@utils/url/upstream';
import { IClientNames, IClientsOvertime } from '@utils/url/upstream.types';
import { getClientsOvertimeUrl as apiUrl } from '@utils/url/api';
/**
* Error message to return to the Requester
*/
interface ErrorMessage {
message: string;
}
export interface IGetRequestData {
/**
* Return formatted data that is compatible with ChartJS
*
* @see {@link https://www.chartjs.org/docs/latest/general/data-structures.html}
* @see {@link https://www.chartjs.org/docs/latest/charts/bar.html#example-dataset-configuration}
*
* @defaultValue `false`
*/
formatted?: string | 'false';
}
/**
* `overtimeDataClients` and `getClientNames` data format obtained from Pi-hole
*/
export type IGetClientsOvertimeResponseData = IClientNames & IClientsOvertime;
export type IGetClientsOvertimeFormatted = ChartData<'bar', number[], number>;
/**
* GET endpoint for `/api/queries/clients/overtime`
*
* Data returned is in raw format
*
* @param req - HTTP request provided by NextJS
* @param res - HTTP response provided by NextJS
*/
const handleGetClientsOvertimeRaw = (
req: NextApiRequest,
res: NextApiResponse<IGetClientsOvertimeResponseData | ErrorMessage>,
) => {
const getLogger = logger.scope(apiUrl, 'GET');
const { ipAddress, port, password } = req.session.authSession;
const requestUrl = new UpstreamApiUrl(ipAddress, port, password).clientOvertimeAndNames();
axios
.get<IGetClientsOvertimeResponseData>(requestUrl)
.then((response) => {
getLogger.info('data obtained from upstream');
res.status(200).json(response.data);
getLogger.complete(`sending response`);
getLogger.debug(`response data: `, response.data);
})
.catch((error) => {
getLogger.error(`error returned when sending HTTP request to '${requestUrl}'`);
res.status(500).json({ message: JSON.stringify(error) });
});
};
/**
* GET endpoint for `/api/queries/clients/overtime`
*
* returns formatted data for ChartJS and react-chartjs-2
*
* @see {@link https://github.com/pi-hole/AdminLTE/blob/master/scripts/pi-hole/js/index.js#L330-L417 | Code inspired by Pi-hole Admin portal}
*
* @param req - HTTP request provided by NextJS
* @param res - HTTP response provided by NextJS
*/
const handleGetClientsOvertimeFormatted = (
req: NextApiRequest,
res: NextApiResponse<IGetClientsOvertimeFormatted | ErrorMessage>,
) => {
const getLogger = logger.scope(apiUrl, 'GET');
const { ipAddress, port, password } = req.session.authSession;
const requestUrl = new UpstreamApiUrl(ipAddress, port, password).clientOvertimeAndNames();
const responseData: IGetClientsOvertimeFormatted = {
labels: [], // unix time
datasets: [],
};
axios
.get<IGetClientsOvertimeResponseData>(requestUrl)
.then((response) => {
getLogger.info('data obtained from upstream');
const timestamps = Object.keys(response.data.over_time);
const plotData = Object.values(response.data.over_time);
const labels: string[] = [];
// add client names as labels
response.data.clients.forEach((client) => {
const clientName = client.name.length > 0 ? client.name : client.ip;
labels.push(clientName);
});
for (let i = 0; i < plotData[0].length; i += 1) {
responseData.datasets.push({
data: [],
// If we ran out of colors, make a random one
backgroundColor:
i < chartThemeColours.length
? chartThemeColours[i]
: `#${(0x1000000 + Math.random() * 0xffffff).toString(16).slice(0, 6)}`,
label: labels[i],
});
}
// Add data for each dataset that is available
timestamps.forEach((e, j) => {
plotData[j].forEach((element, key) => {
responseData.datasets[key].data.push(element);
});
const date = new Date(1000 * parseInt(timestamps[j], 10));
responseData.labels?.push(date.getTime());
});
res.status(200).json(responseData);
getLogger.complete(`sending response`);
})
.catch((error) => {
getLogger.error(`error returned when sending HTTP request to '${requestUrl}'`);
res.status(500).json({ message: JSON.stringify(error) });
});
};
/**
* Default method to run when executing this http api endpoint
*
* @remarks
* HTTP API endpoint `/api/queries/clients/overtime`
*
* @remarks
* HTTP method allowed: `GET`
*/
const requestHandler = (req: NextApiRequest, res: NextApiResponse) => {
const { method = '' } = req;
// limit which HTTP methods are allowed
switch (method) {
case 'GET': {
const { formatted = 'false' } = req.query as IGetRequestData;
if (formatted === 'true') {
handleGetClientsOvertimeFormatted(req, res);
} else {
handleGetClientsOvertimeRaw(req, res);
}
break;
}
default: {
logger.error({
prefix: apiUrl,
message: `invalid HTTP method type '${method}'`,
});
res.setHeader('Allow', ['GET']);
res.status(405).end(`Method ${method} Not Allowed`);
}
}
};
export default withSessionRoute(requestHandler);