2023-07-07 21:56:58 +02:00
|
|
|
const https = require('https');
|
2023-08-09 23:33:36 +02:00
|
|
|
const middleware = require('./_common/middleware');
|
2023-07-07 21:56:58 +02:00
|
|
|
|
2023-08-09 23:33:36 +02:00
|
|
|
const handler = async (url) => {
|
2023-07-07 21:56:58 +02:00
|
|
|
|
|
|
|
// First, get the size of the website's HTML
|
|
|
|
const getHtmlSize = (url) => new Promise((resolve, reject) => {
|
|
|
|
https.get(url, res => {
|
|
|
|
let data = '';
|
|
|
|
res.on('data', chunk => {
|
|
|
|
data += chunk;
|
|
|
|
});
|
|
|
|
res.on('end', () => {
|
|
|
|
const sizeInBytes = Buffer.byteLength(data, 'utf8');
|
|
|
|
resolve(sizeInBytes);
|
|
|
|
});
|
|
|
|
}).on('error', reject);
|
|
|
|
});
|
|
|
|
|
|
|
|
try {
|
|
|
|
const sizeInBytes = await getHtmlSize(url);
|
|
|
|
const apiUrl = `https://api.websitecarbon.com/data?bytes=${sizeInBytes}&green=0`;
|
|
|
|
|
|
|
|
// Then use that size to get the carbon data
|
|
|
|
const carbonData = await new Promise((resolve, reject) => {
|
|
|
|
https.get(apiUrl, res => {
|
|
|
|
let data = '';
|
|
|
|
res.on('data', chunk => {
|
|
|
|
data += chunk;
|
|
|
|
});
|
|
|
|
res.on('end', () => {
|
|
|
|
resolve(JSON.parse(data));
|
|
|
|
});
|
|
|
|
}).on('error', reject);
|
|
|
|
});
|
|
|
|
|
2023-07-29 12:47:03 +02:00
|
|
|
if (!carbonData.statistics || (carbonData.statistics.adjustedBytes === 0 && carbonData.statistics.energy === 0)) {
|
|
|
|
return {
|
|
|
|
statusCode: 200,
|
|
|
|
body: JSON.stringify({ skipped: 'Not enough info to get carbon data' }),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2023-07-07 21:56:58 +02:00
|
|
|
carbonData.scanUrl = url;
|
2023-08-09 23:33:36 +02:00
|
|
|
return carbonData;
|
2023-07-07 21:56:58 +02:00
|
|
|
} catch (error) {
|
2023-08-09 23:33:36 +02:00
|
|
|
throw new Error(`Error: ${error.message}`);
|
2023-07-07 21:56:58 +02:00
|
|
|
}
|
|
|
|
};
|
2023-08-09 23:33:36 +02:00
|
|
|
|
|
|
|
exports.handler = middleware(handler);
|