web-check/api/_common/middleware.js

39 lines
952 B
JavaScript
Raw Normal View History

2023-08-06 23:05:14 +02:00
const normalizeUrl = (url) => {
return url.startsWith('http') ? url : `https://${url}`;
2023-08-06 23:05:14 +02:00
};
const commonMiddleware = (handler) => {
return async (event, context, callback) => {
const rawUrl = (event.queryStringParameters || event.query).url;
if (!rawUrl) {
2023-08-06 23:05:14 +02:00
callback(null, {
statusCode: 500,
body: JSON.stringify({ error: 'No URL specified' }),
2023-08-06 23:05:14 +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;