Skip to content

Commit af428bb

Browse files
Merge pull request #240 from import-ai/refactor/auth
refactor(google): add fetch-with-retry
2 parents 99742f1 + a2f0992 commit af428bb

File tree

2 files changed

+31
-13
lines changed

2 files changed

+31
-13
lines changed

src/auth/google/google.service.ts

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { CreateUserBindingDto } from 'omniboxd/user/dto/create-user-binding.dto'
88
import { Injectable, Logger, HttpStatus } from '@nestjs/common';
99
import { AppException } from 'omniboxd/common/exceptions/app.exception';
1010
import { I18nService } from 'nestjs-i18n';
11+
import { fetchWithRetry } from 'omniboxd/utils/fetch-with-retry';
1112

1213
interface GoogleTokenResponse {
1314
access_token: string;
@@ -103,19 +104,22 @@ export class GoogleService {
103104
);
104105
}
105106

106-
const tokenResponse = await fetch(`${this.googleOAuthAPIBaseUrl}/token`, {
107-
method: 'POST',
108-
headers: {
109-
'Content-Type': 'application/x-www-form-urlencoded',
107+
const tokenResponse = await fetchWithRetry(
108+
`${this.googleOAuthAPIBaseUrl}/token`,
109+
{
110+
method: 'POST',
111+
headers: {
112+
'Content-Type': 'application/x-www-form-urlencoded',
113+
},
114+
body: new URLSearchParams({
115+
client_id: this.clientId,
116+
client_secret: this.clientSecret,
117+
code: code,
118+
grant_type: 'authorization_code',
119+
redirect_uri: this.redirectUri,
120+
}),
110121
},
111-
body: new URLSearchParams({
112-
client_id: this.clientId,
113-
client_secret: this.clientSecret,
114-
code: code,
115-
grant_type: 'authorization_code',
116-
redirect_uri: this.redirectUri,
117-
}),
118-
});
122+
);
119123

120124
if (!tokenResponse.ok) {
121125
const providerName = this.i18n.t('auth.providers.google');
@@ -139,7 +143,7 @@ export class GoogleService {
139143
);
140144
}
141145

142-
const userInfoResponse = await fetch(
146+
const userInfoResponse = await fetchWithRetry(
143147
`${this.googleAPIBaseUrl}/oauth2/v3/userinfo`,
144148
{
145149
headers: { Authorization: `Bearer ${tokenData.access_token}` },

src/utils/fetch-with-retry.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
export async function fetchWithRetry(
2+
url: string,
3+
options?: RequestInit,
4+
maxRetries = 2,
5+
): Promise<Response> {
6+
for (let i = 0; i < maxRetries; i++) {
7+
try {
8+
return await fetch(url, options);
9+
} catch {
10+
// ignore the error
11+
}
12+
}
13+
return await fetch(url, options);
14+
}

0 commit comments

Comments
 (0)