2023-08-06 23:05:14 +02:00
|
|
|
const normalizeUrl = (url) => {
|
2023-08-09 23:31:47 +02:00
|
|
|
return url.startsWith('http') ? url : `https://${url}`;
|
2023-08-06 23:05:14 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
const commonMiddleware = (handler) => {
|
|
|
|
return async (event, context, callback) => {
|
2023-08-09 23:31:47 +02:00
|
|
|
|
|
|
|
const rawUrl = (event.queryStringParameters || event.query).url;
|
|
|
|
|
|
|
|
if (!rawUrl) {
|
2023-08-06 23:05:14 +02:00
|
|
|
callback(null, {
|
2023-08-09 23:31:47 +02:00
|
|
|
statusCode: 500,
|
|
|
|
body: JSON.stringify({ error: 'No URL specified' }),
|
2023-08-06 23:05:14 +02:00
|
|
|
});
|
2023-08-09 23:31:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const url = normalizeUrl(rawUrl);
|
|
|
|
|
|
|
|
try {
|
|
|
|
const response = await handler(url, event, context);
|
|
|
|
if (response.body && response.statusCode) {
|
|
|
|
callback(null, response);
|
|
|
|
} else {
|
|
|
|
callback(null, {
|
|
|
|
statusCode: 200,
|
|
|
|
body: typeof response === 'object' ? JSON.stringify(response) : response,
|
|
|
|
});
|
|
|
|
}
|
2023-08-06 23:05:14 +02:00
|
|
|
} catch (error) {
|
|
|
|
callback(null, {
|
|
|
|
statusCode: 500,
|
|
|
|
body: JSON.stringify({ error: error.message }),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = commonMiddleware;
|