forked from cerebral/overmind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
327 lines (285 loc) · 8.54 KB
/
index.ts
File metadata and controls
327 lines (285 loc) · 8.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import * as withAbsintheSocket from '@absinthe/socket';
import { GraphQLClient } from 'graphql-request';
import * as Dom from 'graphql-request/dist/types.dom';
import { print } from 'graphql/language/printer';
import { Socket as PhoenixSocket } from 'phoenix';
import gqlTag from 'graphql-tag';
import { GraphQLError } from 'graphql';
export interface Query<Result extends any, Payload extends any = void> {
(payload: Payload): Result;
}
type Variable = string | number | boolean | null;
interface NoPayloadSubscription<R> {
(action: (result: R) => void): void;
dispose(): void;
disposeWhere(cb: (variables: { [variables: string]: Variable }) => boolean);
}
interface PayloadSubscription<P, R> {
(payload: P, action: (result: R) => void): void;
dispose(): void;
disposeWhere(cb: (variables: { [variables: string]: Variable }) => boolean);
}
interface Subscription {
variables: { [key: string]: Variable };
dispose: () => void;
}
type Http = {
endpoint: string;
headers?: () => Dom.RequestInit['headers'];
options?: Dom.RequestInit;
};
type Ws =
| {
endpoint: string;
params?: () => { [key: string]: string | number | boolean };
}
| (() => PhoenixSocket | null);
type Queries = {
rawQueries?: {
[key: string]: (payload: any) => any;
};
queries?: {
[key: string]: (payload: any) => any;
};
rawMutations?: {
[key: string]: (payload: any) => any;
};
mutations?: {
[key: string]: (payload: any) => any;
};
subscriptions?: {
[key: string]: (payload: any) => any;
};
};
type RawResult<T extends any> = Promise<{
data?: T;
extensions?: any;
headers: Dom.Headers;
status: number;
errors?: GraphQLError[];
}>
export type Graphql<T extends Queries> = {
initialize(http: Http, ws?: Ws): void;
} & {
rawQueries: {
[N in keyof T['rawQueries']]: T['rawQueries'][N] extends (
payload: infer P
) => infer R
? P extends void
? () => RawResult<R>
: (payload: P) => RawResult<R>
: never;
}
queries: {
[N in keyof T['queries']]: T['queries'][N] extends (
payload: infer P
) => infer R
? P extends void
? () => Promise<R>
: (payload: P) => Promise<R>
: never;
};
rawMutations: {
[N in keyof T['rawMutations']]: T['rawMutations'][N] extends (
payload: infer P
) => infer R
? P extends void
? () => RawResult<R>
: (payload: P) => RawResult<R>
: never;
}
mutations: {
[N in keyof T['mutations']]: T['mutations'][N] extends (
payload: infer P
) => infer R
? P extends void
? () => Promise<R>
: (payload: P) => Promise<R>
: never;
};
subscriptions: {
[N in keyof T['subscriptions']]: T['subscriptions'][N] extends (
payload: infer P
) => infer R
? P extends void
? NoPayloadSubscription<R>
: PayloadSubscription<P, R>
: never;
};
};
function createError(message: string) {
throw new Error(`OVERMIND-GRAPHQL: ${message}`);
}
export const gql = (literals: string | readonly string[], ...placeholders: any[]): Query<any, any> => gqlTag(literals, ...placeholders) as any
const _clients: { [url: string]: GraphQLClient } = {};
const _subscriptions: {
[query: string]: Subscription[];
} = {};
export const graphql: <T extends Queries>(
queries: T
) => Graphql<T> = queries => {
let _http: Http;
let _ws: Ws;
function getClient(): GraphQLClient | null {
if (_http) {
const headers = // eslint-disable-next-line
typeof _http.headers === 'function'
? _http.headers()
: _http.options && _http.options.headers
? _http.options.headers
: {};
if (_clients[_http.endpoint]) {
_clients[_http.endpoint].setHeaders(headers);
} else {
_clients[_http.endpoint] = new GraphQLClient(_http.endpoint, {
..._http.options,
headers,
});
}
return _clients[_http.endpoint];
}
return null;
}
let wsClient: PhoenixSocket | null = null;
function getWsClient(): PhoenixSocket | null {
if (_ws && !wsClient) {
const socket =
typeof _ws === 'function'
? _ws()
: new PhoenixSocket(_ws.endpoint, {
params: _ws.params ? _ws.params() : undefined,
});
if (!socket) {
throw createError(
'You are trying to create a Socket for subscriptions, but there is no socket or socket information provided'
);
}
wsClient = withAbsintheSocket.create(socket);
return wsClient;
}
return wsClient;
}
const evaluatedQueries = {
rawQueries: Object.keys(queries.rawQueries || {}).reduce((aggr, key) => {
aggr[key] = variables => {
const query = queries.rawQueries![key] as any;
const client = getClient();
if (client) {
return client.rawRequest(print(query), variables);
}
throw createError(
'You are running a query, though there is no HTTP endpoint configured'
);
};
return aggr;
}, {}),
queries: Object.keys(queries.queries || {}).reduce((aggr, key) => {
aggr[key] = variables => {
const query = queries.queries![key] as any;
const client = getClient();
if (client) {
return client.request(print(query), variables);
}
throw createError(
'You are running a query, though there is no HTTP endpoint configured'
);
};
return aggr;
}, {}),
rawMutations: Object.keys(queries.rawMutations || {}).reduce((aggr, key) => {
aggr[key] = variables => {
const query = queries.rawMutations![key] as any;
const client = getClient();
if (client) {
return client.rawRequest(print(query), variables);
}
throw createError(
'You are running a query, though there is no HTTP endpoint configured'
);
};
return aggr;
}, {}),
mutations: Object.keys(queries.mutations || {}).reduce((aggr, key) => {
aggr[key] = variables => {
const query = queries.mutations![key] as any;
const client = getClient();
if (client) {
return client.request(print(query), variables);
}
throw createError(
'You are running a query, though there is no HTTP endpoint configured'
);
};
return aggr;
}, {}),
subscriptions: Object.keys(queries.subscriptions || {}).reduce(
(aggr, key) => {
const query = queries.subscriptions![key] as any;
const queryString = print(query);
if (!_subscriptions[queryString]) {
_subscriptions[queryString] = [];
}
function subscription(arg1, arg2) {
const client = getWsClient();
if (client) {
const variables = arg2 ? arg1 : {};
const action = arg2 || arg1;
const notifier = withAbsintheSocket.send(client, {
operation: queryString,
variables,
});
const observer = withAbsintheSocket.observe(client, notifier, {
onResult: ({ data }) => {
action(data);
},
});
_subscriptions[queryString].push({
variables,
dispose: () =>
withAbsintheSocket.unobserve(client, notifier, observer),
});
} else {
throw createError('There is no ws client available for this query');
}
}
subscription.dispose = () => {
_subscriptions[queryString].forEach(sub => {
try {
sub.dispose();
} catch (e) {
// Ignore, it probably throws an error because we weren't subscribed in the first place
}
});
_subscriptions[queryString].length = 0;
};
subscription.disposeWhere = cb => {
_subscriptions[queryString] = _subscriptions[queryString].reduce<
Subscription[]
>((subAggr, sub) => {
if (cb(sub.variables)) {
try {
sub.dispose();
} catch (e) {
// Ignore, it probably throws an error because we weren't subscribed in the first place
}
return subAggr;
}
return subAggr.concat(sub);
}, []);
};
aggr[key] = subscription;
return aggr;
},
{}
),
};
return {
initialize(http: Http, ws?: Ws) {
_http = http;
if (ws) {
_ws = ws;
}
},
...evaluatedQueries,
} as any;
};