Skip to content

Instantly share code, notes, and snippets.

@kocisov
Created August 20, 2021 15:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kocisov/af70830e32a2881bf159f36fe6252925 to your computer and use it in GitHub Desktop.
Save kocisov/af70830e32a2881bf159f36fe6252925 to your computer and use it in GitHub Desktop.
Urql client with @n1ru4l/live-query + json patch (over WS or SSE)
import { applyLiveQueryJSONPatch } from "@n1ru4l/graphql-live-query-patch-json-patch";
import {
applyAsyncIterableIteratorToSink,
makeAsyncIterableIteratorFromSink,
} from "@n1ru4l/push-pull-async-iterable-iterator";
import { createClient as createWSClient } from "graphql-ws";
import {
cacheExchange,
createClient,
dedupExchange,
subscriptionExchange,
} from "urql";
const ws =
typeof window !== "undefined" &&
createWSClient({
url: "wss://api0",
});
export const overWebSocketClient = createClient({
url: "null",
exchanges: [
dedupExchange,
cacheExchange,
subscriptionExchange({
enableAllOperations: true,
forwardSubscription: (operation) => ({
subscribe: (sink) => ({
unsubscribe: applyAsyncIterableIteratorToSink(
applyLiveQueryJSONPatch(
makeAsyncIterableIteratorFromSink((sink) =>
ws.subscribe(operation, sink)
)
),
sink
),
}),
}),
})
]
})
export const overServerSentEventsClient = createClient({
url: "null",
exchanges: [
dedupExchange,
cacheExchange,
subscriptionExchange({
enableAllOperations: true,
forwardSubscription: (operation) => ({
subscribe: (sink) => ({
unsubscribe: applyAsyncIterableIteratorToSink(
applyLiveQueryJSONPatch(
makeAsyncIterableIteratorFromSink((sink) => {
const { unsubscribe } = new Subscription({
url: "https://api0",
searchParams: {
query: operation.query,
variables: JSON.stringify(operation.variables ?? "{}"),
},
onNext: (value) => {
sink.next(JSON.parse(value));
},
onError: sink.error,
onComplete: sink.complete,
});
return unsubscribe;
})
),
sink
),
}),
}),
}),
]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment