-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.tsx
142 lines (124 loc) · 4.66 KB
/
client.tsx
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
import { HttpLink, InMemoryCache, ApolloClient } from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
import { ApolloLink, concat, split } from 'apollo-link';
import { WebSocketLink } from 'apollo-link-ws';
import fetch from 'node-fetch';
import path from 'path';
import { debug } from './debug';
import {createNetworkStatusNotifier} from 'react-apollo-network-status';
import { NetworkStatus, UseApolloNetworkStatusOptions } from 'react-apollo-network-status/dist/src/useApolloNetworkStatus';
const moduleLog = debug.extend('client')
let ws;
if (typeof(window) !== 'object') {
ws = require('ws');
}
const DEEP_FOUNDATION_HASURA_RELATIVE: boolean | undefined = ((r) => r ? !!+r : undefined)(process.env.DEEP_FOUNDATION_HASURA_RELATIVE);
const NEXT_PUBLIC_DEEP_FOUNDATION_HASURA_RELATIVE: boolean | undefined = ((r) => r ? !!+r : undefined)(process.env.NEXT_PUBLIC_DEEP_FOUNDATION_HASURA_RELATIVE);
const ENV_RELATIVE = typeof(DEEP_FOUNDATION_HASURA_RELATIVE) === 'boolean' ? DEEP_FOUNDATION_HASURA_RELATIVE : typeof(NEXT_PUBLIC_DEEP_FOUNDATION_HASURA_RELATIVE) === 'boolean' ? NEXT_PUBLIC_DEEP_FOUNDATION_HASURA_RELATIVE : undefined;
export interface IApolloClientGeneratorOptions {
initialStore?: any;
token?: string;
client?: string;
secret?: string;
ssl?: boolean;
path?: string;
headers?: any;
ws?: boolean;
relative?: boolean;
}
export function generateHeaders(options: IApolloClientGeneratorOptions) {
const headers: IApolloClientGeneratorOptions['headers'] = { ...options.headers };
if (options.token) headers.Authorization = `Bearer ${options.token}`;
if (options.secret) headers['x-hasura-admin-secret'] = options.secret;
if (options.client) headers['x-hasura-client'] = options.client;
return headers;
}
export interface IApolloClient<T> extends ApolloClient<T> {
jwt_token?: string;
path?: string;
ssl?: boolean;
useApolloNetworkStatus?: (options?: UseApolloNetworkStatusOptions | undefined) => NetworkStatus;
}
const host = typeof(window) === 'object' ? window.location.host : '';
export function generateApolloClient(
options: IApolloClientGeneratorOptions,
forwardingArguments?: {
ApolloClient?: any;
InMemoryCache?: any;
},
): ApolloClient<any> {
const log = moduleLog.extend(generateApolloClient.name)
log({options, forwardingArguments});
const isRelative = typeof(options?.relative) === 'boolean' ? options.relative : typeof(ENV_RELATIVE) === 'boolean' ? ENV_RELATIVE : false;
const headers = generateHeaders(options);
const httpLink = new HttpLink({
uri: `${isRelative ? '' : `http${options.ssl ? 's' : ''}:/`}${path.normalize('/' + (options.path || ''))}`,
// @ts-ignore
fetch,
headers,
});
const wsLink = options.ws
? new WebSocketLink({
uri: `${isRelative ? (host ? `ws${options.ssl ? 's' : ''}://${host}` : '') : `ws${options.ssl ? 's' : ''}:/`}${path.normalize('/' + (options.path || ''))}`,
options: {
lazy: true,
reconnect: true,
connectionParams: () => ({
headers,
}),
},
webSocketImpl: ws,
})
: null;
const authMiddleware = new ApolloLink((operation, forward) => {
operation.setContext({
headers,
});
return forward(operation);
});
const link = !options.ws
? httpLink
: split(
({ query }) => {
// return true;
// if you need ws only for subscriptions:
const def = getMainDefinition(query);
return def?.kind === 'OperationDefinition' && def?.operation === 'subscription';
},
wsLink,
// @ts-ignore
httpLink,
);
const {link: notifierLink, useApolloNetworkStatus} = createNetworkStatusNotifier();
const client: IApolloClient<any> = new ApolloClient({
ssrMode: true,
// @ts-ignore
link: concat(notifierLink, concat(authMiddleware, link)),
connectToDevTools: true,
cache: new InMemoryCache({
...forwardingArguments?.InMemoryCache,
freezeResults: false,
resultCaching: false,
}).restore(options.initialStore || {}),
...forwardingArguments?.ApolloClient,
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache',
// errorPolicy: 'ignore',
...forwardingArguments?.ApolloClient?.defaultOptions?.watchQuery,
},
query: {
fetchPolicy: 'no-cache',
// errorPolicy: 'ignore',
...forwardingArguments?.ApolloClient?.defaultOptions?.query,
},
...forwardingArguments?.ApolloClient?.defaultOptions,
},
});
client.jwt_token = options.token;
client.path = options.path;
client.ssl = options.ssl;
client.useApolloNetworkStatus = useApolloNetworkStatus;
log({ client });
return client;
}