Created
April 14, 2022 16:23
-
-
Save beardedtim/e7183c034be26bc1ef960be22a38f181 to your computer and use it in GitHub Desktop.
Waits for a URL to return 200 for a specified time, exits 1 if it is not available
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Wait For It | |
* | |
* Given Env Vars of: | |
* | |
* - VALIDATE_URL: a fully qualified url starting with https:// that we want to validate | |
* - TIME_ALLOWED_IN_SECONDS: timeout we want to wait until we mark this URL dead. Defaults 30 | |
* - TIME_BETWEEN_TRIES_IN_SECONDS: timeout between requests to the URL. Defaults to 1 | |
*/ | |
const https = require('https') | |
const getCurrentTimeInSeconds = () => Date.now() / 1000 | |
let start = getCurrentTimeInSeconds() | |
const timeAllowedInSeconds = Number(process.env.TIME_ALLOWED_IN_SECONDS || 30) | |
const timeToWaitInSeconds = Number( | |
process.env.TIME_BETWEEN_TRIES_IN_SECONDS || 1 | |
) | |
const runIn = (ms) => | |
setTimeout(() => { | |
console.log('Requesting ', process.env.VALIDATE_URL) | |
https.get(process.env.VALIDATE_URL, (res) => { | |
if (res.statusCode !== 200) { | |
console.log('URL Not Validated', res.statusCode) | |
if (getCurrentTimeInSeconds() > timeAllowedInSeconds + start) { | |
console.log( | |
`Failed for timeout of "${timeAllowedInSeconds}" seconds. Failing exit code 1` | |
) | |
process.exit(1) | |
} else { | |
runIn(ms) | |
} | |
} else { | |
console.log('URL Validated') | |
process.exit(0) | |
} | |
}) | |
}, ms) | |
runIn(timeToWaitInSeconds * 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment