Skip to content

Instantly share code, notes, and snippets.

@gbalbuena
Last active October 25, 2019 04:22
Show Gist options
  • Save gbalbuena/ddc81df81c3de78f52aa586d217c909f to your computer and use it in GitHub Desktop.
Save gbalbuena/ddc81df81c3de78f52aa586d217c909f to your computer and use it in GitHub Desktop.
lambda to test health of services like postgres, redis, sqs
const pg = require('pg');
const asyncRedis = require("async-redis");
const key = "HEALTH_CHECK";
async function check_redis() {
const client = asyncRedis.createClient();
client.on("error", (err) => {
throw err
});
await client.set(key, JSON.stringify({ success: true }), 'EX', 1); // 1 sec
const val = await client.get(key);
client.quit();
return JSON.parse(val);
}
async function check_postgres() {
const conn = 'postgres://postgres:changeme@localhost:5432/postgres';
const client = new pg.Client(conn);
client.connect();
const res = await client.query('SELECT 1 + 2 AS success');
client.end();
return res.rows[0].success ==3 ? { success: true } : 0;
}
function successfulResponse(body) {
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
};
}
async function handler(event, context) {
return {
status: 'ok',
redis: await check_redis(),
postgres: await check_postgres()
};
}
async function api_handler(event, context) {
return successfulResponse(await handler(event, context));
}
api_handler().then((v) => { console.log(v.body) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment