Skip to content

Commit e7eb345

Browse files
committed
Add urql ActionCable subscription client
1 parent 04104f1 commit e7eb345

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { Consumer, Subscription } from "@rails/actioncable";
2+
import Urql from "urql"
3+
4+
type ForwardCallback = (...args: any[]) => void
5+
6+
const createUrqlActionCableSubscription = {
7+
create(options: { consumer: Consumer }) {
8+
const consumer = options.consumer
9+
let subscription: Subscription | null = null;
10+
return function(operation: Urql.Operation) {
11+
// urql will call `.subscribed` on the returned object:
12+
// https://github.com/FormidableLabs/urql/blob/f89cfd06d9f14ae9cb3be10b21bd5cbd12ca275c/packages/core/src/exchanges/subscription.ts#L68-L73
13+
// https://github.com/FormidableLabs/urql/blob/f89cfd06d9f14ae9cb3be10b21bd5cbd12ca275c/packages/core/src/exchanges/subscription.ts#L82-L97
14+
return {
15+
subscribe: ({next, error, complete}: { next: ForwardCallback, error: ForwardCallback, complete: ForwardCallback}) => {
16+
subscription = consumer.subscriptions.create("GraphqlChannel", {
17+
connected() {
18+
this.perform("execute", { query: operation.query, variables: operation.variables });
19+
},
20+
disconnected() {
21+
console.log("Subscription disconnected");
22+
},
23+
received(data: any) {
24+
if (data?.result?.errors) {
25+
error(data.errors);
26+
}
27+
if (data?.result?.data) {
28+
next(data.result)
29+
}
30+
if (!data.more) {
31+
complete()
32+
}
33+
}
34+
})
35+
// urql will call `.unsubscribe()` if it's returned here:
36+
// https://github.com/FormidableLabs/urql/blob/f89cfd06d9f14ae9cb3be10b21bd5cbd12ca275c/packages/core/src/exchanges/subscription.ts#L102
37+
return {
38+
unsubscribe: () => {
39+
if (subscription) {
40+
subscription.unsubscribe();
41+
subscription = null;
42+
}
43+
}
44+
}
45+
}
46+
}
47+
}
48+
}
49+
}
50+
51+
export default createUrqlActionCableSubscription

0 commit comments

Comments
 (0)