Skip to content

Instantly share code, notes, and snippets.

@scalabl3
Last active January 3, 2019 21:43
Show Gist options
  • Save scalabl3/04d4a29f43a0b36008f18aa408fcbf54 to your computer and use it in GitHub Desktop.
Save scalabl3/04d4a29f43a0b36008f18aa408fcbf54 to your computer and use it in GitHub Desktop.
Functions XHR Request with Retries
export default (request) => {
const kvstore = require('kvstore');
const xhr = require('xhr');
const vault = require('vault'); // You can use the Vault to store a header/key for your backend
// to validate the request with, alternatively you can use IP whitelist
const host = 'https://f8234c78.ngrok.io';
var url = host + '/v1/webhooks/pubnub';
// test 400
url = "http://httpbin.org/status/400"
// test 404
//url = "http://httpbin.org/status/404"
// test 500
//url = "http://httpbin.org/status/500"
const max_retries = 2; // XHR Limit is 3, PubNub can increase this by emailing [email protected]
const timeout = 5000; // 5 Second Timeout, Total Timeout can't be more than 10 seconds or Function auto-terminates
const http_options = {
'timeout': timeout,
"method": "POST",
"headers": {
"API_KEY": "x",
'Content-Type': 'application/json'
},
'body': request.message
};
function recursiveFetch(url, http_options, retries) {
if (!retries) {
retries = 0;
}
if (retries === max_retries) {
throw new Error("Out of retries");
return request.ok();
}
return xhr.fetch(url, http_options).then((resp) => {
console.log(`XHR ${retries+1}: ${resp.status}`);
if (resp.status != 200) {
return recursiveFetch(url, http_options, ++retries);
} else {
return resp;
}
});
}
return vault.get("apiKey").then((apiKey) => {
http_options.headers.API_KEY = apiKey;
http_options.body.api_key = apiKey;
console.log(request.message);
return recursiveFetch(url, http_options);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment