Skip to content

Commit 51aad5b

Browse files
committed
Replace native fetch with ofetch
Signed-off-by: Ryan Wang <i@ryanc.cc>
1 parent 5f5c604 commit 51aad5b

12 files changed

Lines changed: 126 additions & 118 deletions

File tree

.vscode/settings.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,10 @@
55
"source.fixAll.biome": "explicit",
66
"source.organizeImports.biome": "explicit"
77
}
8-
}
8+
},
9+
"i18n-ally.localesPaths": [
10+
"packages/comment-widget/src/locale",
11+
"workplace/themes/theme-earth/i18n",
12+
"packages/comment-widget/src/generated/locales"
13+
]
914
}

packages/comment-widget/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@
4444
"emoji-mart": "^5.6.0",
4545
"es-toolkit": "^1.39.8",
4646
"javascript-time-ago": "^2.5.11",
47-
"lit": "^3.3.1"
47+
"lit": "^3.3.1",
48+
"ofetch": "^1.4.1"
4849
},
4950
"devDependencies": {
5051
"@iconify/json": "^2.2.367",

packages/comment-widget/src/base-form.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import baseStyles from './styles/base';
2121
import varStyles from './styles/var';
2222
import type { ConfigMapData } from './types';
2323
import './comment-editor';
24+
import { ofetch } from 'ofetch';
2425
import type { CommentEditor } from './comment-editor';
2526

2627
export class BaseForm extends LitElement {
@@ -112,16 +113,19 @@ export class BaseForm extends LitElement {
112113
return;
113114
}
114115

115-
const response = await fetch(
116-
`/apis/api.commentwidget.halo.run/v1alpha1/captcha/-/generate`
117-
);
116+
try {
117+
const data = await ofetch(
118+
`/apis/api.commentwidget.halo.run/v1alpha1/captcha/-/generate`,
119+
{
120+
parseResponse: (txt) => txt,
121+
}
122+
);
118123

119-
if (!response.ok) {
124+
this.captcha = data;
125+
} catch (error) {
126+
console.error(error);
120127
this.toastManager?.error(msg('Failed to obtain verification code'));
121-
return;
122128
}
123-
124-
this.captcha = await response.text();
125129
}
126130

127131
handleOpenLoginPage() {

packages/comment-widget/src/comment-form.ts

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { state } from 'lit/decorators.js';
55
import { createRef, type Ref, ref } from 'lit/directives/ref.js';
66
import './base-form';
77
import { msg } from '@lit/localize';
8+
import { FetchError, type FetchResponse, ofetch } from 'ofetch';
89
import type { BaseForm } from './base-form';
910
import {
1011
allowAnonymousCommentsContext,
@@ -17,7 +18,11 @@ import {
1718
versionContext,
1819
} from './context';
1920
import type { ToastManager } from './lit-toast';
20-
import { getCaptchaCodeHeader, isRequireCaptcha } from './utils/captcha';
21+
import {
22+
type CaptchaRequiredResponse,
23+
getCaptchaCodeHeader,
24+
isRequireCaptcha,
25+
} from './utils/captcha';
2126

2227
export class CommentForm extends LitElement {
2328
@consume({ context: baseUrlContext })
@@ -114,33 +119,19 @@ export class CommentForm extends LitElement {
114119
}
115120

116121
try {
117-
const response = await fetch(
122+
const newComment = await ofetch<Comment>(
118123
`${this.baseUrl}/apis/api.halo.run/v1alpha1/comments`,
119124
{
120125
method: 'POST',
121126
headers: {
122-
'Content-Type': 'application/json',
123127
...getCaptchaCodeHeader(data.captchaCode),
124128
},
125-
body: JSON.stringify(commentRequest),
129+
body: commentRequest,
126130
}
127131
);
128132

129-
if (isRequireCaptcha(response)) {
130-
const { captcha, detail } = await response.json();
131-
this.captcha = captcha;
132-
this.toastManager?.warn(detail);
133-
return;
134-
}
135-
136133
this.baseFormRef.value?.handleFetchCaptcha();
137134

138-
if (!response.ok) {
139-
throw new Error(msg('Comment failed, please try again later'));
140-
}
141-
142-
const newComment = (await response.json()) as Comment;
143-
144135
if (newComment.spec.approved) {
145136
this.toastManager?.success(msg('Comment submitted successfully'));
146137
} else {
@@ -160,9 +151,21 @@ export class CommentForm extends LitElement {
160151

161152
this.baseFormRef.value?.resetForm();
162153
} catch (error) {
163-
if (error instanceof Error) {
164-
this.toastManager?.error(error.message);
154+
if (error instanceof FetchError) {
155+
if (
156+
isRequireCaptcha(
157+
error.response as FetchResponse<CaptchaRequiredResponse>
158+
)
159+
) {
160+
const { captcha, detail } =
161+
error.data as unknown as CaptchaRequiredResponse;
162+
this.captcha = captcha;
163+
this.toastManager?.warn(detail);
164+
return;
165+
}
165166
}
167+
168+
this.toastManager?.error(msg('Comment failed, please try again later'));
166169
} finally {
167170
this.submitting = false;
168171
}

packages/comment-widget/src/comment-item.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import './base-comment-item-action';
99
import { consume } from '@lit/context';
1010
import { msg } from '@lit/localize';
1111
import { createRef, type Ref, ref } from 'lit/directives/ref.js';
12+
import { ofetch } from 'ofetch';
1213
import { getPolicyInstance } from './avatar/avatar-policy';
1314
import type { CommentReplies } from './comment-replies';
1415
import { LS_UPVOTED_COMMENTS_KEY } from './constant';
@@ -79,12 +80,9 @@ export class CommentItem extends LitElement {
7980
group: 'content.halo.run',
8081
};
8182

82-
await fetch(`${this.baseUrl}/apis/api.halo.run/v1alpha1/trackers/upvote`, {
83+
await ofetch(`${this.baseUrl}/apis/api.halo.run/v1alpha1/trackers/upvote`, {
8384
method: 'POST',
84-
headers: {
85-
'Content-Type': 'application/json',
86-
},
87-
body: JSON.stringify(voteRequest),
85+
body: voteRequest,
8886
});
8987

9088
upvotedComments.push(this.comment?.metadata.name);

packages/comment-widget/src/comment-list.ts

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type { ConfigMapData } from './types';
1919
import './comment-pagination';
2020
import './comment-item';
2121
import './loading-block';
22+
import { ofetch } from 'ofetch';
2223

2324
export class CommentList extends LitElement {
2425
@consume({ context: baseUrlContext })
@@ -106,34 +107,28 @@ export class CommentList extends LitElement {
106107
this.comments.page = page;
107108
}
108109

109-
const queryParams = [
110-
`group=${this.group}`,
111-
`kind=${this.kind}`,
112-
`name=${this.name}`,
113-
`page=${this.comments.page}`,
114-
`size=${this.configMapData?.basic.size || 20}`,
115-
`version=${this.version}`,
116-
`withReplies=${this.configMapData?.basic.withReplies || false}`,
117-
`replySize=${this.configMapData?.basic.replySize || 10}`,
118-
];
119-
120-
const response = await fetch(
121-
`${this.baseUrl}/apis/api.halo.run/v1alpha1/comments?${queryParams.join(
122-
'&'
123-
)}`
110+
const data = await ofetch<CommentVoList>(
111+
`${this.baseUrl}/apis/api.halo.run/v1alpha1/comments`,
112+
{
113+
query: {
114+
group: this.group,
115+
kind: this.kind,
116+
name: this.name,
117+
page: this.comments.page,
118+
size: this.configMapData?.basic.size || 20,
119+
version: this.version,
120+
withReplies: this.configMapData?.basic.withReplies || false,
121+
replySize: this.configMapData?.basic.replySize || 10,
122+
},
123+
}
124124
);
125125

126-
if (!response.ok) {
127-
throw new Error(
128-
msg('Failed to load comment list, please try again later')
129-
);
130-
}
131-
132-
this.comments = await response.json();
133-
} catch (error) {
134-
if (error instanceof Error) {
135-
this.toastManager?.error(error.message);
136-
}
126+
this.comments = data;
127+
} catch (_error) {
128+
console.error(_error);
129+
this.toastManager?.error(
130+
msg('Failed to load comment list, please try again later')
131+
);
137132
} finally {
138133
this.loading = false;
139134

packages/comment-widget/src/comment-replies.ts

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import './reply-item';
88
import './loading-block';
99
import './reply-form';
1010
import { msg } from '@lit/localize';
11+
import { ofetch } from 'ofetch';
1112
import type { ToastManager } from './lit-toast';
1213
import baseStyles from './styles/base';
1314
import varStyles from './styles/var';
@@ -94,25 +95,18 @@ export class CommentReplies extends LitElement {
9495
this.page = 1;
9596
}
9697

97-
const queryParams = [
98-
`page=${this.page || 1}`,
99-
`size=${this.configMapData?.basic.replySize || 10}`,
100-
];
101-
102-
const response = await fetch(
98+
const data = await ofetch<ReplyVoList>(
10399
`${this.baseUrl}/apis/api.halo.run/v1alpha1/comments/${
104100
this.comment?.metadata.name
105-
}/reply?${queryParams.join('&')}`
101+
}/reply`,
102+
{
103+
query: {
104+
page: this.page || 1,
105+
size: this.configMapData?.basic.replySize || 10,
106+
},
107+
}
106108
);
107109

108-
if (!response.ok) {
109-
throw new Error(
110-
msg('Failed to load reply list, please try again later')
111-
);
112-
}
113-
114-
const data = (await response.json()) as ReplyVoList;
115-
116110
if (options?.append) {
117111
this.replies = this.replies.concat(data.items);
118112
} else {
@@ -122,9 +116,10 @@ export class CommentReplies extends LitElement {
122116
this.hasNext = data.hasNext;
123117
this.page = data.page;
124118
} catch (error) {
125-
if (error instanceof Error) {
126-
this.toastManager?.error(error.message);
127-
}
119+
console.error(error);
120+
this.toastManager?.error(
121+
msg('Failed to load reply list, please try again later')
122+
);
128123
} finally {
129124
this.loading = false;
130125
}

packages/comment-widget/src/comment-widget.ts

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { User } from '@halo-dev/api-client';
1+
import type { DetailedUser, User } from '@halo-dev/api-client';
22
import { provide } from '@lit/context';
33
import { css, html, LitElement } from 'lit';
44
import { property, state } from 'lit/decorators.js';
@@ -29,6 +29,7 @@ import baseStyles from './styles/base';
2929
import varStyles from './styles/var';
3030
import type { ConfigMapData } from './types';
3131
import './comment-list';
32+
import { ofetch } from 'ofetch';
3233

3334
export class CommentWidget extends LitElement {
3435
@provide({ context: baseUrlContext })
@@ -84,31 +85,21 @@ export class CommentWidget extends LitElement {
8485
}
8586

8687
async fetchGlobalInfo() {
87-
try {
88-
const response = await fetch(`${this.baseUrl}/actuator/globalinfo`, {
89-
method: 'get',
90-
credentials: 'same-origin',
91-
});
92-
93-
const data = await response.json();
94-
this.allowAnonymousComments = data.allowAnonymousComments;
95-
} catch (error) {
96-
console.error('Failed to fetch global info', error);
97-
}
88+
const data = await ofetch(`${this.baseUrl}/actuator/globalinfo`);
89+
this.allowAnonymousComments = data.allowAnonymousComments;
9890
}
9991

10092
async fetchConfigMapData() {
101-
const response = await fetch(
93+
const data = await ofetch<ConfigMapData>(
10294
`${this.baseUrl}/apis/api.commentwidget.halo.run/v1alpha1/config`
10395
);
104-
this.configMapData = (await response.json()) as ConfigMapData;
96+
this.configMapData = data;
10597
}
10698

10799
async fetchCurrentUser() {
108-
const response = await fetch(
100+
const data = await ofetch<DetailedUser>(
109101
`${this.baseUrl}/apis/api.console.halo.run/v1alpha1/users/-`
110102
);
111-
const data = await response.json();
112103
this.currentUser =
113104
data.user.metadata.name === 'anonymousUser' ? undefined : data.user;
114105
}

0 commit comments

Comments
 (0)