Skip to content

Instantly share code, notes, and snippets.

@reidstidolph
Created December 21, 2019 00:47
Show Gist options
  • Save reidstidolph/7fe50b9a765db318f697705ab2fbdada to your computer and use it in GitHub Desktop.
Save reidstidolph/7fe50b9a765db318f697705ab2fbdada to your computer and use it in GitHub Desktop.
Promise-based sample fetching node status from the 128T REST API.
/*******************************************************************************
* *
* Promise-based sample fetching node status 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 node status for
const nodeName = 'node1' // Node name to retrieve status from
// set up HTTP(S) request options
let reqOptions = {
host : host128t,
path : `/api/v1/router/${routerName}/node/${nodeName}`,
method : 'GET',
headers : {
'accept' : 'application/json',
'authorization' : `Bearer ${tokenString}`
},
rejectUnauthorized : false
}
// Promise returning function to get status
const getNodeStatus = 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 node status
getNodeStatus()
.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