|
| 1 | +import { |
| 2 | + GraphQLResponse, |
| 3 | + Observable, |
| 4 | + RequestParameters, |
| 5 | + Variables, |
| 6 | +} from "relay-runtime"; |
| 7 | +import { createClient } from "graphql-ws"; |
| 8 | +import { Repeater } from "@repeaterjs/repeater"; |
| 9 | +import { applySourceToSink } from "./shared"; |
| 10 | +import { makeAsyncIterableIteratorFromSink } from "@n1ru4l/push-pull-async-iterable-iterator"; |
| 11 | + |
| 12 | +function makeEventStreamSource(url: string) { |
| 13 | + return new Repeater<GraphQLResponse>(async (push, end) => { |
| 14 | + const eventsource = new EventSource(url); |
| 15 | + eventsource.onmessage = function (event) { |
| 16 | + const data = JSON.parse(event.data); |
| 17 | + push(data); |
| 18 | + if (eventsource.readyState === 2) { |
| 19 | + end(); |
| 20 | + } |
| 21 | + }; |
| 22 | + eventsource.onerror = function (event) { |
| 23 | + console.log("Error", event); |
| 24 | + end(new Error("Check the console bruv.")); |
| 25 | + }; |
| 26 | + await end; |
| 27 | + |
| 28 | + eventsource.close(); |
| 29 | + }); |
| 30 | +} |
| 31 | + |
| 32 | +export function createWSFetcher(url: string) { |
| 33 | + const client = createClient({ url }); |
| 34 | + return ( |
| 35 | + request: RequestParameters, |
| 36 | + variables: Variables |
| 37 | + ): Observable<GraphQLResponse> => { |
| 38 | + if (!request.text) throw new Error("Missing document."); |
| 39 | + const { text: operation, name } = request; |
| 40 | + |
| 41 | + return Observable.create<GraphQLResponse>((sink) => { |
| 42 | + const source = makeAsyncIterableIteratorFromSink((sink) => { |
| 43 | + return client.subscribe<GraphQLResponse>( |
| 44 | + { variables, query: operation }, |
| 45 | + { |
| 46 | + next: sink.next.bind(sink), |
| 47 | + complete: sink.complete.bind(sink), |
| 48 | + error: sink.error.bind(sink), |
| 49 | + } |
| 50 | + ); |
| 51 | + }); |
| 52 | + |
| 53 | + return applySourceToSink(source, sink); |
| 54 | + }); |
| 55 | + }; |
| 56 | +} |
0 commit comments