diff options
Diffstat (limited to 'frontend/src/api.js')
| -rw-r--r-- | frontend/src/api.js | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/frontend/src/api.js b/frontend/src/api.js index 479f0ef..87ec685 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -65,4 +65,51 @@ export const api = { } return response.json(); }, + + /** + * Send a message and receive streaming updates. + * @param {string} conversationId - The conversation ID + * @param {string} content - The message content + * @param {function} onEvent - Callback function for each event: (eventType, data) => void + * @returns {Promise<void>} + */ + async sendMessageStream(conversationId, content, onEvent) { + const response = await fetch( + `${API_BASE}/api/conversations/${conversationId}/message/stream`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ content }), + } + ); + + if (!response.ok) { + throw new Error('Failed to send message'); + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + try { + const event = JSON.parse(data); + onEvent(event.type, event); + } catch (e) { + console.error('Failed to parse SSE event:', e); + } + } + } + } + }, }; |
