mirror of
https://github.com/Lissy93/web-check.git
synced 2025-08-27 03:54:20 +02:00
Moves API handlers from server/lambda to /api
This commit is contained in:
55
api/get-carbon.js
Normal file
55
api/get-carbon.js
Normal file
@@ -0,0 +1,55 @@
|
||||
const https = require('https');
|
||||
|
||||
exports.handler = async (event, context) => {
|
||||
const { url } = event.queryStringParameters;
|
||||
|
||||
if (!url) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
body: JSON.stringify({ error: 'url query parameter is required' }),
|
||||
};
|
||||
}
|
||||
|
||||
// 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);
|
||||
});
|
||||
|
||||
carbonData.scanUrl = url;
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: JSON.stringify(carbonData),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
statusCode: 500,
|
||||
body: JSON.stringify({ error: `Error: ${error.message}` }),
|
||||
};
|
||||
}
|
||||
};
|
Reference in New Issue
Block a user