assembly-payments
Version:
Assembly Payments API Typescript/Javascript Bindings
36 lines (35 loc) • 1.78 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.expiredToken = void 0;
function expiredToken(client, retries = 5) {
return client.instance.interceptors.response.use(undefined, async (error) => {
var _a, _b, _c, _d;
const { config } = error;
const connectionError = error && ['ECONNABORTED', 'ECONNREFUSED'].includes(error.code);
if (connectionError) {
return Promise.reject(error);
}
if (!config) {
return Promise.reject(error);
}
config.expiredTokenRetry = config.expiredTokenRetry || 0;
const accessDenied = ((_b = (_a = error === null || error === void 0 ? void 0 : error.data) === null || _a === void 0 ? void 0 : _a.errors) === null || _b === void 0 ? void 0 : _b.token) === 'is not authorized';
const status = (_c = error === null || error === void 0 ? void 0 : error.response) === null || _c === void 0 ? void 0 : _c.status;
const canTry = !config.expiredTokenRetry || config.expiredTokenRetry < retries;
if (!accessDenied && status === 401 && canTry) {
config.expiredTokenRetry += 1;
client.logger.debug(`requested failed, refreshing token attempt ${config.expiredTokenRetry}`);
try {
await client.refresh();
config.headers.Authorization = `Bearer ${(_d = client === null || client === void 0 ? void 0 : client.token) === null || _d === void 0 ? void 0 : _d.access_token}`;
return client.instance(config);
}
catch (e) {
return Promise.reject(e);
}
}
return Promise.reject(error);
});
}
exports.expiredToken = expiredToken;
exports.default = expiredToken;
;