UNPKG

@memori.ai/memori-react

Version:

[![npm version](https://img.shields.io/github/package-json/v/memori-ai/memori-react)](https://www.npmjs.com/package/@memori.ai/memori-react) ![Tests](https://github.com/memori-ai/memori-react/workflows/CI/badge.svg?branch=main) ![TypeScript Support](https

72 lines 3.01 kB
import { useEffect, useRef, useState, useCallback } from 'react'; import { getNatsConfig } from './getNatsConfig'; import { useNatsSession, } from './useNatsSession'; export function useNats({ baseUrl, sessionId, onProgress, onDialogResponse, onError, }) { const [config, setConfig] = useState(null); const [configError, setConfigError] = useState(null); const onProgressRef = useRef(onProgress); const onDialogResponseRef = useRef(onDialogResponse); const onErrorRef = useRef(onError); useEffect(() => { onProgressRef.current = onProgress; onDialogResponseRef.current = onDialogResponse; onErrorRef.current = onError; }, [onProgress, onDialogResponse, onError]); useEffect(() => { if (!sessionId) { console.debug('[NATS] no sessionId, skipping config fetch'); setConfig(null); setConfigError(null); return; } const controller = new AbortController(); let cancelled = false; console.info('[NATS] fetching config from', `${baseUrl}/api/nats`, 'for session', sessionId); getNatsConfig(baseUrl, sessionId, controller.signal) .then(cfg => { if (!cancelled) { console.info('[NATS] config received', { url: cfg.url, jetStream: !!cfg.stream, stream: cfg.stream, }); setConfig(cfg); setConfigError(null); } }) .catch(err => { if (!cancelled && (err === null || err === void 0 ? void 0 : err.name) !== 'AbortError') { console.error('[NATS] config error', err); setConfig(null); setConfigError(err instanceof Error ? err : new Error(String(err))); } }); return () => { cancelled = true; controller.abort(); }; }, [baseUrl, sessionId]); const handleMessage = useCallback((event) => { var _a, _b, _c; console.debug('[NATS] dispatching event', { eventType: event.eventType }); switch (event.eventType) { case 'progress': (_a = onProgressRef.current) === null || _a === void 0 ? void 0 : _a.call(onProgressRef, event); break; case 'dialog_text_entered_response': (_b = onDialogResponseRef.current) === null || _b === void 0 ? void 0 : _b.call(onDialogResponseRef, event); break; case 'error': (_c = onErrorRef.current) === null || _c === void 0 ? void 0 : _c.call(onErrorRef, event); break; default: console.warn('Unknown NATS event', event); } }, []); useNatsSession(sessionId, config !== null && config !== void 0 ? config : undefined, handleMessage); return { connected: !!config, configError, }; } //# sourceMappingURL=useNats.js.map