2023-06-30 00:40:06 +02:00
|
|
|
const https = require('https');
|
|
|
|
const { performance, PerformanceObserver } = require('perf_hooks');
|
2023-08-09 23:33:36 +02:00
|
|
|
const middleware = require('./_common/middleware');
|
2023-06-30 00:40:06 +02:00
|
|
|
|
2023-09-03 13:27:04 +02:00
|
|
|
const handler = async (url) => {
|
2023-06-30 00:40:06 +02:00
|
|
|
if (!url) {
|
2023-08-09 23:33:36 +02:00
|
|
|
throw new Error('You must provide a URL query parameter!');
|
2023-06-30 00:40:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
let dnsLookupTime;
|
|
|
|
let responseCode;
|
2023-07-10 00:23:50 +02:00
|
|
|
let startTime;
|
2023-06-30 00:40:06 +02:00
|
|
|
|
|
|
|
const obs = new PerformanceObserver((items) => {
|
|
|
|
dnsLookupTime = items.getEntries()[0].duration;
|
|
|
|
performance.clearMarks();
|
|
|
|
});
|
|
|
|
|
|
|
|
obs.observe({ entryTypes: ['measure'] });
|
|
|
|
|
|
|
|
performance.mark('A');
|
|
|
|
|
2023-07-10 00:23:50 +02:00
|
|
|
try {
|
|
|
|
startTime = performance.now();
|
|
|
|
const response = await new Promise((resolve, reject) => {
|
|
|
|
const req = https.get(url, res => {
|
|
|
|
let data = '';
|
|
|
|
responseCode = res.statusCode;
|
|
|
|
res.on('data', chunk => {
|
|
|
|
data += chunk;
|
|
|
|
});
|
|
|
|
res.on('end', () => {
|
|
|
|
resolve(res);
|
2023-06-30 00:40:06 +02:00
|
|
|
});
|
|
|
|
});
|
2023-07-10 00:23:50 +02:00
|
|
|
|
|
|
|
req.on('error', reject);
|
|
|
|
req.end();
|
2023-06-30 00:40:06 +02:00
|
|
|
});
|
2023-07-10 00:23:50 +02:00
|
|
|
|
|
|
|
if (responseCode < 200 || responseCode >= 400) {
|
2023-08-09 23:33:36 +02:00
|
|
|
throw new Error(`Received non-success response code: ${responseCode}`);
|
2023-07-10 00:23:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
performance.mark('B');
|
|
|
|
performance.measure('A to B', 'A', 'B');
|
|
|
|
let responseTime = performance.now() - startTime;
|
|
|
|
obs.disconnect();
|
|
|
|
|
2023-08-09 23:33:36 +02:00
|
|
|
return { isUp: true, dnsLookupTime, responseTime, responseCode };
|
2023-07-10 00:23:50 +02:00
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
obs.disconnect();
|
2023-08-09 23:33:36 +02:00
|
|
|
throw error;
|
2023-07-10 00:23:50 +02:00
|
|
|
}
|
2023-06-30 00:40:06 +02:00
|
|
|
};
|
2023-08-09 23:33:36 +02:00
|
|
|
|
2023-09-03 13:27:04 +02:00
|
|
|
module.exports = middleware(handler);
|
|
|
|
module.exports.handler = middleware(handler);
|