@splitsoftware/splitio-commons
Version:
Split JavaScript SDK common components
36 lines (35 loc) • 1.97 kB
JavaScript
import { __assign } from "tslib";
import { splitHttpClientFactory } from './splitHttpClient';
import { authProviderFactory } from './authProvider';
/**
* Factory of Secure HTTP client, which authenticates requests using a JWT token.
* On 401 responses, invalidates the cached credential and retries once with a fresh token.
*
* @param settings - SDK settings
* @param platform - object containing environment-specific dependencies
* @param fetchAuth - function to fetch auth credentials from the /v2/auth endpoint
*/
export function secureSplitHttpClientFactory(settings, platform, telemetryTracker) {
var splitHttpClient = splitHttpClientFactory(settings, platform);
var authProvider = authProviderFactory(settings, splitHttpClient, telemetryTracker);
function makeRequest(url, options, latencyTracker, logErrorsAsInfo, token) {
return splitHttpClient(url, __assign(__assign({}, options), { headers: __assign(__assign({}, options === null || options === void 0 ? void 0 : options.headers), { Authorization: "Bearer ".concat(token) }) }), latencyTracker, logErrorsAsInfo, true);
}
var httpClient = function (url, options, latencyTracker, logErrorsAsInfo) {
return authProvider.credential().then(function (credential) {
return makeRequest(url, options, latencyTracker, logErrorsAsInfo, credential.token)
.catch(function (error) {
if (error.statusCode === 401) {
// retry once for 401, in case the token has just expired
authProvider.invalidate();
return authProvider.credential().then(function (newCredential) {
return makeRequest(url, options, latencyTracker, logErrorsAsInfo, newCredential.token);
});
}
throw error;
});
});
};
httpClient.stop = function () { return authProvider.stop(); };
return httpClient;
}