Skip to content

Instantly share code, notes, and snippets.

@DinoChiesa
Created October 21, 2024 17:33
Show Gist options
  • Save DinoChiesa/25ee61025c3a19f9aaee94072b5b907f to your computer and use it in GitHub Desktop.
Save DinoChiesa/25ee61025c3a19f9aaee94072b5b907f to your computer and use it in GitHub Desktop.
Apigee JS httpClient with retry
// getTokenWithRetry.js
// ------------------------------------------------------------------
//
// Example JS policy configuration:
//
// Note: you need the authUrl Property.
//
// <Javascript name='JS-Retrieve-Token' timeLimit='12000' >
// <Properties>
// <Property name='authUrl'>https://url-for-token-endpoint/token</Property>
// </Properties>
// <ResourceURL>jsc://getTokenWithRetry.js</ResourceURL>
// </Javascript>
//
/* jshint esversion:6, node:false, strict:implied */
/* global print, context, properties, httpClient, Request */
var MAX_CYCLES = 3;
var cycleCount = 0;
// fill the following with what you need
var headers = {};
var payload = "";
/*
* The callback invoked after an httpClient call completes.
* If the call was not successful, conditionally retry.
* If successful or if retry limit has been reached, set a context variable and return.
*
*/
function onComplete(response, error) {
cycleCount++;
if (error || response.status != 200) {
// error => no response, call failed. Maybe a network error?
// status!= 200 => response, but not successful.
if (cycleCount < MAX_CYCLES) {
sendOne();
return;
}
}
// If reaching here, either the call was successful, or we reached the limit
// of retries after error. Either way, set variables and terminate the chain.
context.setVariable("token-response-tries", cycleCount.toFixed(0));
if (response.content) {
context.setVariable("token-response-content", response.content);
}
return;
}
function sendOne() {
var req = new Request(String(properties.authUrl), "POST", headers, payload);
httpClient.send(req, onComplete);
}
sendOne();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment