Skip to content

Commit 963586b

Browse files
feat(overmind-graphql): allow passing existing socket for subscriptions
1 parent f3c5a66 commit 963586b

File tree

1 file changed

+31
-15
lines changed
  • packages/node_modules/overmind-graphql/src

1 file changed

+31
-15
lines changed

packages/node_modules/overmind-graphql/src/index.ts

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,12 @@ type Http = {
3838
options?: Options;
3939
};
4040

41-
type Ws = {
42-
endpoint: string;
43-
params?: () => { [key: string]: string | number | boolean };
44-
};
41+
type Ws =
42+
| {
43+
endpoint: string;
44+
params?: () => { [key: string]: string | number | boolean };
45+
}
46+
| (() => PhoenixSocket | null);
4547

4648
type Queries = {
4749
queries?: {
@@ -92,7 +94,6 @@ function createError(message: string) {
9294
}
9395

9496
const _clients: { [url: string]: GraphQLClient } = {};
95-
const _wsClients: { [url: string]: PhoenixSocket } = {};
9697
const _subscriptions: {
9798
[query: string]: Subscription[];
9899
} = {};
@@ -127,20 +128,26 @@ export const graphql: <T extends Queries>(
127128
return null;
128129
}
129130

131+
let wsClient: PhoenixSocket | null = null;
130132
function getWsClient(): PhoenixSocket | null {
131-
if (_ws) {
132-
if (!_wsClients[_ws.endpoint]) {
133-
_wsClients[_ws.endpoint] = withAbsintheSocket.create(
134-
new PhoenixSocket(_ws.endpoint, {
135-
params: _ws.params ? _ws.params() : undefined,
136-
})
133+
if (_ws && !wsClient) {
134+
const socket =
135+
typeof _ws === 'function'
136+
? _ws()
137+
: new PhoenixSocket(_ws.endpoint, {
138+
params: _ws.params ? _ws.params() : undefined,
139+
});
140+
141+
if (!socket) {
142+
throw createError(
143+
'You are trying to create a Socket for subscriptions, but there is no socket or socket information provided'
137144
);
138145
}
139-
140-
return _wsClients[_ws.endpoint];
146+
wsClient = withAbsintheSocket.create(socket);
147+
return wsClient;
141148
}
142149

143-
return null;
150+
return wsClient;
144151
}
145152

146153
const evaluatedQueries = {
@@ -212,7 +219,11 @@ export const graphql: <T extends Queries>(
212219

213220
subscription.dispose = () => {
214221
_subscriptions[queryString].forEach(sub => {
215-
sub.dispose();
222+
try {
223+
sub.dispose();
224+
} catch (e) {
225+
// Ignore, it probably throws an error because we weren't subscribed in the first place
226+
}
216227
});
217228
_subscriptions[queryString].length = 0;
218229
};
@@ -222,6 +233,11 @@ export const graphql: <T extends Queries>(
222233
Subscription[]
223234
>((subAggr, sub) => {
224235
if (cb(sub.variables)) {
236+
try {
237+
sub.dispose();
238+
} catch (e) {
239+
// Ignore, it probably throws an error because we weren't subscribed in the first place
240+
}
225241
return subAggr;
226242
}
227243
return subAggr.concat(sub);

0 commit comments

Comments
 (0)