2024-05-06 22:51:32 +02:00
|
|
|
import https from 'https';
|
|
|
|
import middleware from './_common/middleware.js';
|
2023-07-07 21:56:58 +02:00
|
|
|
|
2024-05-06 22:51:32 +02:00
|
|
|
const carbonHandler = 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
|
|
|
|
2024-05-06 22:51:32 +02:00
|
|
|
export const handler = middleware(carbonHandler);
|
|
|
|
export default handler;
|