UNPKG

@apolitical/health

Version:

Node.js module to expose Apolitical's APIs health checks

52 lines (46 loc) 1.41 kB
'use strict'; module.exports = ({ axios, config }) => { const { APIS, LOCALHOST, HEALTH: { STATUS, NEW_STATUS, ENDPOINT }, } = config; function buildURL(name) { if (!APIS[name]) { throw new Error(`Usupported name`); } const { HOST, PORT, FALLBACK_PORT } = APIS[name]; const url = HOST && PORT ? `http://${HOST}:${PORT}/${ENDPOINT}` : `http://${LOCALHOST}:${FALLBACK_PORT}/${ENDPOINT}`; return url; } function handleError(error, name) { const { message, response, request } = error; let errorMessage = `Service ${name} unhealthy: ${message}`; if (response) { const errorDetails = JSON.stringify({ status: response.status, data: response.data, }); errorMessage += ` - The request was made and the server responded with ${errorDetails}`; } else if (request) { errorMessage += ' - The request was made but no response was received'; } throw new Error(errorMessage); } async function checkHealth(name) { try { const url = buildURL(name); const { data } = await axios.get(url); if (!data) { throw new Error(`Response data undefined`); } if (data.status !== STATUS && data.status !== NEW_STATUS) { throw new Error(`Status is not up`); } } catch (error) { handleError(error, name); } } return { checkHealth }; };