(
url: string,
accessToken: string,
body: SubmitFeedbackBody,
opts: { timeoutMs?: number } = {},
)
| 37 | } |
| 38 | |
| 39 | export async function fetchSubmitFeedback( |
| 40 | url: string, |
| 41 | accessToken: string, |
| 42 | body: SubmitFeedbackBody, |
| 43 | opts: { timeoutMs?: number } = {}, |
| 44 | ): Promise<FetchSubmitFeedbackResult> { |
| 45 | const controller = new AbortController(); |
| 46 | const timer = setTimeout(() => { |
| 47 | controller.abort(); |
| 48 | }, opts.timeoutMs ?? 8000); |
| 49 | try { |
| 50 | const res = await fetch(url, { |
| 51 | method: 'POST', |
| 52 | headers: { |
| 53 | Authorization: `Bearer ${accessToken}`, |
| 54 | Accept: 'application/json', |
| 55 | 'Content-Type': 'application/json', |
| 56 | }, |
| 57 | body: JSON.stringify(body), |
| 58 | signal: controller.signal, |
| 59 | }); |
| 60 | if (!res.ok) { |
| 61 | return { |
| 62 | kind: 'error', |
| 63 | status: res.status, |
| 64 | message: await readApiErrorMessage( |
| 65 | res, |
| 66 | `Failed to submit feedback: HTTP ${String(res.status)}`, |
| 67 | ), |
| 68 | }; |
| 69 | } |
| 70 | const feedbackId = parseFeedbackId(await res.json()); |
| 71 | if (feedbackId === undefined) { |
| 72 | return { kind: 'error', message: 'Failed to submit feedback: missing feedback_id.' }; |
| 73 | } |
| 74 | return { kind: 'ok', feedbackId }; |
| 75 | } catch (error) { |
| 76 | if (error instanceof Error && error.name === 'AbortError') { |
| 77 | return { kind: 'error', message: 'Failed to submit feedback: request timed out.' }; |
| 78 | } |
| 79 | const msg = error instanceof Error ? error.message : String(error); |
| 80 | return { kind: 'error', message: `Failed to submit feedback: ${msg}` }; |
| 81 | } finally { |
| 82 | clearTimeout(timer); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | function parseFeedbackId(payload: unknown): number | undefined { |
| 87 | const direct = readFeedbackId(payload); |
no test coverage detected