const WebSocket = require('websocket').client
const ServersToTest = [ 'testnet.xrpl-labs.com', 's.altnet.rippletest.net:51233' ]
exports.endpoint = (request, response) => {
Promise.all(ServersToTest.map(Server => {
return new Promise((resolve, reject) => {
let WsInstance = new WebSocket()
WsInstance.connect('wss://' + Server)
WsInstance.on('connectFailed', error => {
console.log('Connect Error ' + Server, error.toString())
resolve({ server: Server, status: 'ConnectError', data: null, errorData: error.toString() })
})
WsInstance.on('connect', c => {
// console.log('Connected ' + Server, c)
c.on('message', m => {
let data = JSON.parse(m.utf8Data)
// console.log('Message ' + Server, data)
resolve({ server: Server, status: 'Response', data: data, errorData: null })
c.close()
})
c.on('close', () => {
// console.log('Closed ' + Server)
})
c.on('error', e => {
console.log('Error ' + Server, e.toString())
resolve({ server: Server, status: 'MsgError', data: null, errorData: e.toString() })
})
c.send(JSON.stringify({ command: 'server_info' }))
setTimeout(() => {
c.close()
resolve({ server: Server, status: 'Timeout', data: null, errorData: null })
}, 5000)
})
})
})).then(Results => {
// Running in the browser, respond
let highestLedger = Math.max.apply(Math, Results.filter(r => {
return r.status === 'Response' && r.data !== null && r.data.result.info.complete_ledgers.match(/[0-9]/)
}).map(r => {
return parseInt(r.data.result.info.complete_ledgers.split(',').reverse()[0].split('-').reverse()[0])
}).filter(r => {
return !isNaN(r)
}))
let OutputData = {
highestLedger: highestLedger,
responses: Object.assign({}, ...Results.map(r => {
let lastLedger = 0
if (r.data !== null) {
lastLedger = parseInt(r.data.result.info.complete_ledgers.split(',').reverse()[0].split('-').reverse()[0])
if (isNaN(lastLedger)) lastLedger = 0
}
return {
[r.server.replace(/[^a-z0-9]/g, '')]: Object.assign(r, {
lastLedger: lastLedger,
ledgerOffset: highestLedger - lastLedger
})
}
}))
}
if (response !== null) {
response.end(JSON.stringify(OutputData))
} else {
// Running in the console. Log.
console.log('Done', OutputData)
}
}).catch(Error => {
})
}
// When in the browser...
exports.endpoint(null, null)