2019-06-25 05:06:28 +02:00
|
|
|
/**
|
|
|
|
* helpers.js
|
|
|
|
*
|
|
|
|
* Additional state-less helper methods.
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Makes a AJAX request, streaming each line as it arrives. Type should be text/plain,
|
|
|
|
* each line will be interpreted as JSON separately.
|
|
|
|
*
|
|
|
|
* @param path The path to connect to.
|
|
|
|
* @param callback A callback with a JSON payload. Called for every line as it comes.
|
|
|
|
* @param successCallback A callback with a raw text payload.
|
|
|
|
* @param failCallback A fail callback. Optional.
|
|
|
|
* @param data POST data. Optional.
|
|
|
|
*/
|
|
|
|
export function stream_ajax (path, callback, successCallback, failCallback, data) {
|
2022-03-31 11:41:39 +02:00
|
|
|
const req = new XMLHttpRequest()
|
2019-06-25 05:06:28 +02:00
|
|
|
|
|
|
|
console.log('Making streaming HTTP request to ' + path)
|
|
|
|
|
|
|
|
req.addEventListener('load', function () {
|
|
|
|
// The server can sometimes return a string error. Make sure we handle this.
|
|
|
|
if (this.status === 200) {
|
|
|
|
successCallback(this.responseText)
|
|
|
|
} else {
|
|
|
|
failCallback(this.responseText)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2022-03-31 11:41:39 +02:00
|
|
|
let buffer = ''
|
|
|
|
let seenBytes = 0
|
2019-06-25 05:06:28 +02:00
|
|
|
|
|
|
|
req.onreadystatechange = function () {
|
|
|
|
if (req.readyState > 2) {
|
|
|
|
buffer += req.responseText.substr(seenBytes)
|
|
|
|
|
2022-03-31 11:41:39 +02:00
|
|
|
let pointer
|
2019-06-25 05:06:28 +02:00
|
|
|
while ((pointer = buffer.indexOf('\n')) >= 0) {
|
2022-03-31 11:41:39 +02:00
|
|
|
const line = buffer.substring(0, pointer).trim()
|
2019-06-25 05:06:28 +02:00
|
|
|
buffer = buffer.substring(pointer + 1)
|
|
|
|
|
|
|
|
if (line.length === 0) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-03-31 11:41:39 +02:00
|
|
|
const contents = JSON.parse(line)
|
2019-06-25 05:06:28 +02:00
|
|
|
callback(contents)
|
|
|
|
}
|
|
|
|
|
|
|
|
seenBytes = req.responseText.length
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
req.addEventListener('error', failCallback)
|
|
|
|
|
2019-12-10 09:02:12 +01:00
|
|
|
req.open(data == null ? 'GET' : 'POST', path + '?nocache=' + Date.now(), true)
|
2019-06-25 05:06:28 +02:00
|
|
|
// Rocket only currently supports URL encoded forms.
|
|
|
|
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
|
|
|
|
|
|
|
|
if (data != null) {
|
2022-03-31 11:41:39 +02:00
|
|
|
let form = ''
|
2019-06-25 05:06:28 +02:00
|
|
|
|
2022-03-31 11:41:39 +02:00
|
|
|
for (const key in data) {
|
2020-05-28 08:37:20 +02:00
|
|
|
if (!data[key]) {
|
2019-06-25 05:06:28 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if (form !== '') {
|
|
|
|
form += '&'
|
|
|
|
}
|
|
|
|
|
|
|
|
form += encodeURIComponent(key) + '=' + encodeURIComponent(data[key])
|
|
|
|
}
|
|
|
|
|
|
|
|
req.send(form)
|
|
|
|
} else {
|
|
|
|
req.send()
|
|
|
|
}
|
|
|
|
}
|