Skip to content

Instantly share code, notes, and snippets.

@scvnc
Created May 26, 2023 14:55
Show Gist options
  • Save scvnc/7809a02801d81693b97aee667e60ebfb to your computer and use it in GitHub Desktop.
Save scvnc/7809a02801d81693b97aee667e60ebfb to your computer and use it in GitHub Desktop.
Fiddle with async iterable or other @bufbuild/connect-web vue binding
import { ConnectError } from '@bufbuild/connect-web';
import { Ref, ref } from 'vue';
const useStreamingCall = <T>(controllerFn: StreamingCallController<T>) => {
const currentData = ref<T | undefined>(); // todo: optionally not make undefined
const cancel = controllerFn(
(data: T) => {
currentData.value = data;
// do something with data
},
error => {
if (error) {
// handle error
}
// reconnect/retry/backoff logic?
}
);
// TODO: retry/backoff/fail
// TODO: signal when it is reconnecting
// TODO: how to pause and reconnect
// TODO: disconnect streaming endpoint when scope is disposed
const paused = ref(false);
const reconnecting = ref(false);
const error = ref(false);
return { currentData, paused, reconnecting, error };
};
const useAsyncIterable = <T>(asyncItr: AsyncIterable<T>, initialValue: T) => {
const currentValue: Ref<T> = ref(initialValue) as Ref<T>;
(async () => {
for await (const nextVal of asyncItr) {
const _nextVal: T = nextVal;
currentValue.value = _nextVal;
}
})();
return { data: currentValue };
};
type CancelFn = () => void;
type StreamingCallController<T> = (
onData: (data: T) => void,
onClose: (error: ConnectError | undefined) => void
) => CancelFn;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment