Skip to content

Commit

Permalink
Cleaner serverless function
Browse files Browse the repository at this point in the history
  • Loading branch information
wilwade committed Sep 16, 2024
1 parent 0dae54b commit 300f61a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 39 deletions.
71 changes: 33 additions & 38 deletions cors-proxy/index.mjs
Original file line number Diff line number Diff line change
@@ -1,49 +1,44 @@
import https from 'node:https';
import process from 'node:process';

export const handler = async (event) => {
const targetUrl = process.env.PROXY_TARGET_URL;

const postData = event.body;

const options = {
const response = await fetch(targetUrl, {
method: 'POST',
body: event.body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-type': 'application/x-www-form-urlencoded',
},
};

return new Promise((resolve, _reject) => {
const req = https.request(targetUrl, options, (response) => {
let data = '';

// Collect response data
response.on('data', (chunk) => (data += chunk));

// When the request is complete
response.on('end', () => {
resolve({
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
status: response.statusCode,
headers: response.headers,
body: data,
}),
});
});
});

req.on('error', (error) => {
resolve({
statusCode: 500,
body: JSON.stringify({ message: 'Error in request', error: error.message }),
});
});
mode: 'no-cors',
});

req.write(postData);
req.end();
if (response.status >= 200 && response.status < 300) {
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
status: response.status,
body: await response.text(),
}),
};
}

console.error('Received an error response', {
statusCode: response.status,
message: response.message,
headers: response.headers,
});

return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
error: 'Failed to submit form',
status: response.status,
}),
};
};
2 changes: 1 addition & 1 deletion cors-proxy/serverless.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ provider:
runtime: nodejs20.x

functions:
proxy:
cors-proxy:
handler: index.handler
events:
- http:
Expand Down

0 comments on commit 300f61a

Please sign in to comment.