Skip to content

Commit e3e0c1d

Browse files
committed
Implement retry logic for error 401
1 parent 427c49a commit e3e0c1d

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@rantalainen/lemonsoft-api-client",
3-
"version": "1.0.2",
3+
"version": "1.0.3",
44
"description": "",
55
"main": "dist/index.js",
66
"scripts": {

src/index.ts

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,26 @@ export class LemonsoftApiClient {
112112
private installErrorHandler() {
113113
this.api.instance.interceptors.response.use(
114114
(response) => response,
115-
(error) => {
116-
error.message =
117-
`Lemonsoft HTTP error ${error.response.status} (${error.response.statusText}): ` + JSON.stringify(error.response.data);
115+
async (error) => {
116+
const originalRequest = error.config;
117+
// Only retry once to avoid infinite loops
118+
if (error.response && error.response.status === 401 && !originalRequest._retry) {
119+
originalRequest._retry = true;
120+
this.sessionId = undefined; // Clear session to force re-login
121+
// Re-authenticate (get new sessionId)
122+
await this.securityWorker(this);
123+
// Set new sessionId header
124+
originalRequest.headers['Session-Id'] = this.sessionId;
125+
// Retry the original request
126+
return this.api.instance.request(originalRequest);
127+
}
128+
// Default error handling
129+
if (error.response) {
130+
error.message =
131+
`Lemonsoft HTTP error ${error.response.status} (${error.response.statusText}): ` + JSON.stringify(error.response.data);
132+
} else {
133+
error.message = `Lemonsoft HTTP error: No response received. Original error: ${error.message}`;
134+
}
118135
throw error;
119136
}
120137
);
@@ -133,7 +150,7 @@ export class LemonsoftApiClient {
133150

134151
this.sessionId = (response.data as { session_id: string }).session_id;
135152

136-
// Reset the session id after 1 hour (session id is valid for 30 minutes)
153+
// Reset the session id after 20 minutes (session id is valid for 30 minutes)
137154
setTimeout(() => {
138155
this.sessionId = undefined;
139156
}, 20 * 60 * 1000);

0 commit comments

Comments
 (0)