Created
August 20, 2021 15:04
-
-
Save kocisov/af70830e32a2881bf159f36fe6252925 to your computer and use it in GitHub Desktop.
Urql client with @n1ru4l/live-query + json patch (over WS or SSE)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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