Skip to content

Instantly share code, notes, and snippets.

@filipeandre
Created November 20, 2024 17:47
Show Gist options
  • Save filipeandre/9ed27c1aa2a3653a23eca216336c46a6 to your computer and use it in GitHub Desktop.
Save filipeandre/9ed27c1aa2a3653a23eca216336c46a6 to your computer and use it in GitHub Desktop.
Lambda used to check connection
const https = require('https');
exports.handler = async (event) => {
const url = '';
const timeout = 4000; // 4 seconds
return new Promise((resolve) => {
const options = {
method: 'GET',
timeout: timeout,
};
const req = https.request(url, options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve({
statusCode: res.statusCode,
message: 'Successfully connected',
response: data,
});
});
});
req.on('error', (err) => {
const errorDetails = {
statusCode: 500,
message: 'Failed to connect',
reason: err.code || 'Unknown error',
};
if (err.code === 'ENOTFOUND') {
errorDetails.reason = 'DNS resolution failed. The server could not be found.';
} else if (err.code === 'ETIMEDOUT') {
errorDetails.reason = 'Connection timed out.';
} else if (err.code === 'ECONNREFUSED') {
errorDetails.reason = 'Connection refused by the server.';
} else if (err.code === 'EHOSTUNREACH') {
errorDetails.reason = 'Server is unreachable.';
}
resolve(errorDetails);
});
req.on('timeout', () => {
req.destroy();
resolve({
statusCode: 504,
message: 'Failed to connect',
reason: 'Request timed out.',
});
});
req.end();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment