Skip to content

Commit

Permalink
fix: auto logout on api retry error
Browse files Browse the repository at this point in the history
  • Loading branch information
kiettl1-nals committed May 15, 2024
1 parent 870b8b3 commit df04a7e
Showing 1 changed file with 27 additions and 22 deletions.
49 changes: 27 additions & 22 deletions src/runtime/services/HttpService.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { $Fetch, FetchContext, FetchOptions } from "ofetch";
import { navigateTo, useNuxtApp, useRoute } from "#imports";
import { useLocalizeRoute } from "#build/useLocalizeRoute.mjs";
import { middleTruncate, HTTP_STATUS_UNAUTHORIZED, AuthStatus } from "../utils";
import { navigateTo, useNuxtApp, useRoute } from "#imports";
import type { $Fetch, FetchContext, FetchOptions } from "ofetch";
import type { AuthConfig, AuthService } from "../../types";
import { AuthStatus, HTTP_STATUS_UNAUTHORIZED, middleTruncate } from "../utils";

export default class HttpService {
public $fetch!: $Fetch;
Expand Down Expand Up @@ -48,18 +48,23 @@ export default class HttpService {
return;
}

try {
const { token } = await this.$auth.refreshTokens();
const retryOptions = this.buildRetryOptions(options, token);
await this.$fetch(request, {
...retryOptions,
onResponse(ctx) {
Object.assign(context, ctx);
},
});
} catch {
await this.onAuthFailure(AuthStatus.Expired);
const { token } = await this.$auth.refreshTokens().catch(() => ({

token: undefined
}))

if (!token) {
this.onAuthFailure(AuthStatus.Expired)
return;
}

const retryOptions = this.buildRetryOptions(options, token);
await this.$fetch(request, {
...retryOptions,
onResponse(ctx) {
Object.assign(context, ctx);
},
});
},
});
}
Expand Down Expand Up @@ -108,10 +113,10 @@ export default class HttpService {
response.status < 300
? "\x1b[32m✅"
: response.status < 400
? "\x1b[33m👉"
: response.status < 500
? "\x1b[31m❌"
: "\x1b[31m❗️",
? "\x1b[33m👉"
: response.status < 500
? "\x1b[31m❌"
: "\x1b[31m❗️",
response.status,
"\x1B[0m"
);
Expand All @@ -124,10 +129,10 @@ export default class HttpService {
response.status < 300
? "✅"
: response.status < 400
? "👉"
: response.status < 500
? "❌"
: "❗️",
? "👉"
: response.status < 500
? "❌"
: "❗️",
response.status,
previewResponse
);
Expand Down

0 comments on commit df04a7e

Please sign in to comment.