eregistrations-js
Version:
A JavaScript library that simplifies usage of eRegistrations APIs.
51 lines (50 loc) • 1.87 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAccessToken = getAccessToken;
// Cache for storing tokens
const tokenCache = {};
// Get a unique key for the instance configuration
function getInstanceKey(config) {
return `${config.authUrl}|${config.realm}|${config.credentials.clientId}`;
}
async function getAccessToken(config) {
if (config.token)
return config.token;
const instanceKey = getInstanceKey(config);
const cachedToken = tokenCache[instanceKey];
// Check if we have a cached token that's still valid (with 30 second buffer)
if (cachedToken && cachedToken.expiresAt > Date.now() + 30000) {
return cachedToken.token;
}
// No valid token in cache, fetch a new one
try {
const tokenUrl = `${config.authUrl}/realms/${config.realm}/protocol/openid-connect/token`;
const params = new URLSearchParams();
params.append('grant_type', 'client_credentials');
params.append('client_id', config.credentials.clientId);
params.append('client_secret', config.credentials.clientSecret);
const response = await fetch(tokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
});
if (!response.ok) {
throw new Error(`Failed to get access token: ${response.statusText}`);
}
const data = await response.json();
const token = data.access_token;
// Cache the token
const expiresAt = Date.now() + data.expires_in * 1000;
tokenCache[instanceKey] = {
token,
expiresAt,
};
return token;
}
catch (error) {
console.error('Error getting access token:', error);
throw error;
}
}