stash.js (2865B)
1 var Stash = function(inbound, outbound) { 2 this.stashPath = '/presentation-api/receiving-ua/support/stash.py?id='; 3 this.inbound = inbound; 4 this.outbound = outbound; 5 } 6 7 // initialize a stash on wptserve 8 Stash.prototype.init = function() { 9 return Promise.all([ 10 fetch(this.stashPath + this.inbound).then(response => { 11 return response.text(); 12 }), 13 fetch(this.stashPath + this.outbound).then(response => { 14 return response.text(); 15 }) 16 ]); 17 } 18 19 // upload a test result to a stash on wptserve 20 Stash.prototype.send = function(result) { 21 return fetch(this.stashPath + this.outbound, { 22 method: 'POST', 23 body: JSON.stringify({ type: 'data', data: result }) 24 }).then(response => { 25 return response.text(); 26 }).then(text => { 27 return text === 'ok' ? null : Promise.reject(); 28 }) 29 }; 30 31 // upload a test result to a stash on wptserve via navigator.sendBeacon 32 Stash.prototype.sendBeacon = function(result) { 33 if ('sendBeacon' in navigator) { 34 navigator.sendBeacon(this.stashPath + this.outbound, JSON.stringify({ type: 'data', data: result })); 35 } 36 // Note: The following could be discarded, since XHR in synchronous mode is now being deprecated. 37 else { 38 return new Promise(resolve, reject => { 39 const xhr = new XMLHttpRequest(); 40 xhr.open('POST', this.stashPath + this.outbound, false); 41 xhr.send(JSON.stringify({ type: 'data', data: result })); 42 }); 43 } 44 }; 45 46 // wait until a test result is uploaded to a stash on wptserve 47 Stash.prototype.receive = function() { 48 return new Promise((resolve, reject) => { 49 let intervalId; 50 const interval = 500; // msec 51 const polling = () => { 52 return fetch(this.stashPath + this.inbound).then(response => { 53 return response.text(); 54 }).then(text => { 55 if (text) { 56 try { 57 const json = JSON.parse(text); 58 if (json.type === 'data') 59 resolve(json.data); 60 else 61 reject(); 62 } catch(e) { 63 resolve(text); 64 } 65 clearInterval(intervalId); 66 } 67 }); 68 }; 69 intervalId = setInterval(polling, interval); 70 }); 71 }; 72 73 // reset a stash on wptserve 74 Stash.prototype.stop = function() { 75 return Promise.all([ 76 fetch(this.stashPath + this.inbound).then(response => { 77 return response.text(); 78 }), 79 fetch(this.stashPath + this.outbound).then(response => { 80 return response.text(); 81 }) 82 ]).then(() => { 83 return Promise.all([ 84 fetch(this.stashPath + this.inbound, { 85 method: 'POST', 86 body: JSON.stringify({ type: 'stop' }) 87 }).then(response => { 88 return response.text(); 89 }), 90 fetch(this.stashPath + this.outbound, { 91 method: 'POST', 92 body: JSON.stringify({ type: 'stop' }) 93 }).then(response => { 94 return response.text(); 95 }) 96 ]); 97 }); 98 }