Updated middleware to handle various response shapes

This commit is contained in:
Alicia Sykes 2023-08-09 22:31:47 +01:00
parent f0ff33e081
commit 85af5f9327

View File

@ -1,21 +1,31 @@
const normalizeUrl = (url) => { const normalizeUrl = (url) => {
// Normalizing logic here return url.startsWith('http') ? url : `https://${url}`;
return url.startsWith('http') ? url : `http://${url}`;
}; };
const commonMiddleware = (handler) => { const commonMiddleware = (handler) => {
return async (event, context, callback) => { return async (event, context, callback) => {
try {
const rawUrl = event.queryStringParameters.url; const rawUrl = (event.queryStringParameters || event.query).url;
const url = normalizeUrl(rawUrl);
if (!rawUrl) {
// Call the specific handler with the normalized URL
const response = await handler(url, event, context);
callback(null, { callback(null, {
statusCode: 200, statusCode: 500,
body: JSON.stringify(response), body: JSON.stringify({ error: 'No URL specified' }),
}); });
}
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,
});
}
} catch (error) { } catch (error) {
console.log(error); console.log(error);
callback(null, { callback(null, {