Skip to content

Instantly share code, notes, and snippets.

@AaronMcCaughan
Last active August 14, 2019 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AaronMcCaughan/a09c16065c77afcd8eb48190b9589868 to your computer and use it in GitHub Desktop.
Save AaronMcCaughan/a09c16065c77afcd8eb48190b9589868 to your computer and use it in GitHub Desktop.
Environment Health Check - Test Plutora APIs
/**************************************************************
**********ENVIRONMENT HEALTH CHECK SAMPLE SCRIPT *************
**************************************************************
The following scripts executes a plain JS Test script.
The script accepts a URL and API Credentials as parameters passed in from the UI, generates a Oauth token and makes a simple API call
The paramaters entered into the UI need to be named as follows and are case sensitive:
- url = <The API oauth url of your Plutora Instance>
- clientId = <The API clientId for your instance of Plutora>
- clientSecret = <The API clientSecret for your instance of Plutora>
- username = <The email address for your user>
- password = <The password address for your user>
- apiUrl = <The API url of your Plutora Instance>
- failureEmails = <email addresses of selected email recipients if the test fails>
The outcome of your test should return the result via a Promise.Resolve();
resolve('Online'); Sets the environment health status to 'Online'
resolve('Offline'); Sets the environment health status to 'Offline'
resolve('Issue'); Sets the environment health status to 'Issue'
resolve('Unknown'); Sets the environment health status to 'Unknown'
Any thrown errors during script execution or a call to Reject will be treated as a result of Unknown
reject(true); Sets the environment health status to 'Unknown'
The script will trigger an email notification if the test fails to the email address entered in the failureEmails parameter value
*/
const https = require("https");
const querystring = require('querystring');
var parameters;
let run = function (args) {
//Destructure paramaters for local use.
parameters = args.arguments;
return new Promise(async function (resolve, reject) {
console.log('Beginning EnvironmentCheck test');
//Execute the test
let testResult;
getBearerToken().then(token => makeRequest(token, "Releases"))
.then(async result => {
if (result.length > 0) {
console.log("Call successfully completed");
testResult = 'Online';
} else {
console.log("Call did not return a 200 response");
testResult = 'Offline';
}
console.log('Completed EnvironmentCheck test');
//Optional clause to send emails if a test fails to pass.
if (testResult = 'Offline') {
await sendFailureEmail(parameters.failureEmails, "Test completed but the result was a fail.");
}
return resolve(testResult);
})
.catch(async err => {
console.log("Critical error making call");
console.log(err);
//Optional clause to send emails if a test fails to complete.
await sendFailureEmail(parameters.failureEmails, `Test did not complete due to error: ${err}`);
//return resolve(testResult); //This is considered a failed scenario as the API was not accessible.
});
});
};
const getBearerToken = function () {
console.log('Starting Authorisation');
return new Promise(function (resolve, reject) {
let body = "";
const data = querystring.stringify({
client_id: parameters.clientId,
client_secret: parameters.clientSecret,
grant_type: "password",
username: parameters.username,
password: parameters.password
});
const options = {
method: "POST",
"rejectUnauthorized": false,
port: 443,
hostname: parameters.url,
path: "/oauth/token",
headers: {
"Content-Type": 'x-www-form-urlencoded; charset=urf-8',
'Accept': "application/json"
}
};
const req = https.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
try {
console.log("end request");
result = JSON.parse(body);
if (result.access_token) {
console.log("Received token");
resolve(result.access_token);
} else {
reject(JSON.stringify(result));
}
} catch (e) {
console.log("end request catch");
reject(JSON.stringify(body));
}
});
});
req.on('error', (e) => {
reject(JSON.stringify(e));
});
req.write(data);
req.end();
})
};
const makeRequest = function (bearerToken, entity) {
return new Promise(function (resolve, reject) {
console.log(`Making GET request to endpoint: ${entity}`);
const req = https.request({
method: "GET",
hostname: parameters.apiUrl,
port: 443,
path: "/" + entity,
"rejectUnauthorized": false,
headers: {
Authorization: "bearer " + bearerToken
}
}, function (res) {
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
body = JSON.parse(body);
resolve(body);
});
});
req.on('error', (e) => {
reject(JSON.stringify(e));
});
req.write("");
req.end();
});
};
const sendFailureEmail = async function (emails, message = null) {
mailData = {
to: emails, // Required - Address data can be passed as a single string with commas separating addresses or an array of single address strings. ie: ['a@a.com', 'b@b.com']
//cc: 'a@a.com', //optional
//bcc: 'a@a.com', //optional
subject: 'Environment Health Check Failure - SSO_Login', //Required
body: `A failure occured during the execution of this script. <b> Bold Text </b> <i>Italicized text</i> \n\n + ${message}` //Required - This accepts HTML or standard text input.
//signature: '\n\n\nCustom email signature.' //Optional. If excluded a default Plutora signature will be appended.
};
await mailer.send(mailData);
};
module.exports = {
run: run
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment