@@ -5,6 +5,7 @@ import { state } from 'lit/decorators.js';
55import { createRef , type Ref , ref } from 'lit/directives/ref.js' ;
66import './base-form' ;
77import { msg } from '@lit/localize' ;
8+ import { FetchError , type FetchResponse , ofetch } from 'ofetch' ;
89import type { BaseForm } from './base-form' ;
910import {
1011 allowAnonymousCommentsContext ,
@@ -17,7 +18,11 @@ import {
1718 versionContext ,
1819} from './context' ;
1920import 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
2227export 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 }
0 commit comments