1function CPAPIClient() { 2 this._bearer = function () { 3 return localStorage.getItem("ApiBearerToken"); 4 }; 5 6 this._clearBearer = function () { 7 localStorage.removeItem("ApiBearerToken") 8 } 9 10 this._request = function (url, method, payload, callback, error) { 11 var retries = 3; 12 var self = this; 13 payload = payload && typeof payload === "object" ? JSON.stringify(payload) : payload; 14 15 function invokeWithFreshBearer(xhr) { 16 var req = new XMLHttpRequest(); 17 req.open("GET", "/GetBearerToken"); 18 req.addEventListener("load", function () { 19 var bearer = JSON.parse(this.responseText); 20 localStorage.setItem("ApiBearerToken", bearer); 21 xhr.setRequestHeader("Authorization", "Bearer " + bearer); 22 xhr.send(payload); 23 }) 24 req.send(); 25 } 26 27 function makeRequest() { 28 var xhr = new XMLHttpRequest() 29 xhr.open(method, url); 30 xhr.addEventListener("load", function () { 31 if (this.status === 401 && retries > 0) { 32 console.log("Token expired. Retrying...", retries); 33 retries--; 34 self._clearBearer(); 35 makeRequest(); 36 return; 37 } 38 if (this.status >= 400 || retries < 1) { 39 (typeof error === 'function') && error({xhr: this, error: "Request Failed!"}); 40 return; 41 } 42 try { 43 var obj = JSON.parse(this.responseText); 44 callback(obj); 45 } catch (e) { 46 (typeof error === 'function') && error({xhr: this, error: e}); 47 console.error(e); 48 } 49 }); 50 (method === "POST") && xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); 51 var bearer = self._bearer(); 52 if (!bearer) { 53 invokeWithFreshBearer(xhr); 54 return; 55 } 56 xhr.setRequestHeader("Authorization", "Bearer " + bearer); 57 xhr.send(payload); 58 } 59 60 makeRequest(); 61 }; 62 63 this.get = function (url, callback, error) { 64 return this._request(url, "GET", null, callback, error); 65 }; 66 67 this.post = function (url, payload, callback, error) { 68 return this._request(url, "POST", payload, callback, error); 69 } 70}
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.