Created
October 11, 2019 03:31
-
-
Save reidstidolph/f387bbe53b02fe71da1ac5d8195f5a70 to your computer and use it in GitHub Desktop.
Promise-based sample fetching active alarms from the 128T REST API.
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
/******************************************************************************* | |
* * | |
* Promise-based sample fetching active alarms from the 128T REST API. * | |
* * | |
*******************************************************************************/ | |
const https = require('https') | |
const host128t = 'my.128t.host.com' // Address or FQDN of 128T host | |
const tokenString = 'myLongTokenString' // API JWT | |
const routerName = 'my-router-name' // Router name to retrieve alarms for | |
// set up HTTP(S) request options | |
let reqOptions = { | |
host : host128t, | |
path : `/api/v1/router/${routerName}/alarm`, | |
method : 'GET', | |
headers : { | |
'accept' : 'application/json', | |
'authorization' : `Bearer ${tokenString}` | |
}, | |
rejectUnauthorized : false | |
} | |
// Promise returning function to get alarms | |
const getAlarms = function() { | |
return new Promise((resolve, reject) => { | |
const request = https.request(reqOptions, (response) => { | |
// handle http errors | |
if (response.statusCode < 200 || response.statusCode > 299) { | |
reject(new Error('Failed to load page, status code: ' + response.statusCode)) | |
} | |
const body = [] | |
response.on('data', (chunk) => body.push(chunk)) | |
response.on('end', () => resolve(JSON.parse(body.join('')))) | |
}) | |
// handle connection errors | |
request.on('error', (err) => reject(err)) | |
request.end() | |
}) | |
} | |
// Begin getting alarms | |
getAlarms() | |
.then((data) => { | |
// handle results | |
process.stdout.write(`API returned:\n${JSON.stringify(data, null, 2)}\n`) | |
process.exit(0) | |
}) | |
.catch((err) => { | |
// handle error | |
process.stderr.write(`API request failed: ${err}\n`) | |
process.exit(1) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment