Skip to content

Commit

Permalink
Commit missing request.js
Browse files Browse the repository at this point in the history
  • Loading branch information
mafredri committed Dec 6, 2016
1 parent 03fdf7d commit 1b8662d
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions public/openbttn/request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

let requestAuthKey = null;

function request(body, timeout = 5000) {
let xhr = new XMLHttpRequest();
xhr.open('POST', `http://${location.hostname}:8774/socket`);

return new Promise(function (resolve, reject) {
xhr.onload = function (e) {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else if ([400, 403, 500].includes(xhr.status)) {
reject(`${xhr.statusText}: ${xhr.responseText}`);
} else {
reject(`Unknown response: ${xhr.status} ${xhr.statusText} (${xhr.responseText})`)
}
};
xhr.ontimeout = (e) => reject('Request timed out!');
xhr.onerror = (e) => reject('Error communicating with bttn!');

xhr.timeout = timeout;

if (requestAuthKey) {
body = 'auth = ' + requestAuthKey + '\n' + body;
}
xhr.send(body);
});
}

function setRequestAuthKey(key) {
requestAuthKey = key;
}

window.request = request;
window.setRequestAuthKey = setRequestAuthKey;

0 comments on commit 1b8662d

Please sign in to comment.