-
Notifications
You must be signed in to change notification settings - Fork 0
/
Provider.tsx
234 lines (192 loc) · 6.3 KB
/
Provider.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
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
import * as React from 'react';
import { GraphQLStore, StoreState } from './Store';
import {
Context,
Dict,
FetcherConfig,
GraphQLClient,
Method,
Methods
} from './Client';
export const useClient: UseClient = (methodName, initialFetchConfig) => {
const { store, method } = useGraphQLStore(methodName);
// as setState is async, we also save requestSignature in a ref
const requestSignatureRef = React.useRef('');
// to unsubscribe when unmount or when requestSignature changes
const unsubscribeRef = React.useRef(() => {});
// if there is a initialConfig, we generate a default requestSignature with
// this config - otherwise the requestSignature will be set on
// the first request and possible changed with setCacheKey if
// requestSignature changes between fetches or renders
const [requestSignature, updateReqSignatureState] = React.useState(() => {
if (!initialFetchConfig) {
return '';
}
const reqSign = store.mountRequestSignature(
methodName as string,
initialFetchConfig.variables
);
requestSignatureRef.current = reqSign;
return reqSign;
});
const [state, setState] = React.useState<HookState<any, any>>(() => {
const isLoading = !!initialFetchConfig;
// if there is a initial fetch config and cache !== false we have
// a requestSignature at the first render
if (requestSignature) {
const cached = store.getItem(requestSignature);
return storeStateToHookState(cached, isLoading);
}
return storeStateToHookState(undefined, isLoading);
});
// update requestSignature and state
function updateSignature(
{ methodName, variables }: { methodName: string; variables: Dict },
cb?: (newReqSeg: string) => any
) {
const newSignature = store.mountRequestSignature(methodName, variables);
if (newSignature === requestSignatureRef.current) return;
updateReqSignatureState(newSignature);
requestSignatureRef.current = newSignature;
if (cb) cb(newSignature);
}
// subscription
React.useEffect(() => {
unsubscribeRef.current();
unsubscribeRef.current = store.subscribe((value, _requestSignature) => {
if (requestSignatureRef.current !== _requestSignature) {
return;
}
if (
value.context.action !== 'complete' &&
value.context.action !== 'abort'
) {
return;
}
setState(storeStateToHookState(value));
});
return unsubscribeRef.current;
}, []);
const fetcher = (
variables: any = {},
config: Partial<FetcherConfig<any, any>> = {}
) => {
const methodInfo = store.client.methodsInfo[methodName];
if (methodInfo.isQuery) {
// we set loading here because we dont set loading from the above
// subscription - because setting from the subscription will set loading
// for items that not called the current request
if(config.cache === false && !state.loading || state.error) {
setState({ ...state, loading: true });
}
updateSignature({ methodName: methodName as string, variables }, sign => {
const cached = store.getItem(sign);
setState({ ...storeStateToHookState(cached), loading: true });
});
return method(variables, config);
}
if (!state.loading) {
setState({ ...state, loading: true });
}
return method(variables, config).then(ctx => {
setState(
storeStateToHookState({
context: ctx,
loading: false,
resolved: true,
listeners: [],
result: undefined,
error: undefined,
isOptimistic: false
})
);
return ctx;
});
};
// if there is a default fetch config, fetch it on first render
const wasStartedTheDefaultFetch = React.useRef(false);
if (!wasStartedTheDefaultFetch.current && initialFetchConfig) {
wasStartedTheDefaultFetch.current = true;
fetcher(initialFetchConfig.variables, initialFetchConfig.config);
}
return [state, fetcher, store];
};
export const GraphQLStoreContext = React.createContext({} as GraphQLStore);
export class GraphQLProvider extends React.Component<Props> {
store: GraphQLStore;
constructor(props: Props, context: any) {
super(props, context);
this.store = new GraphQLStore({ client: this.props.client });
}
render() {
return React.createElement(GraphQLStoreContext.Provider, {
children: this.props.children,
value: this.store
});
}
}
function useGraphQLStore(methodName: keyof Methods) {
const store = React.useContext(GraphQLStoreContext);
if (!store) {
throw new Error('store is not present in React Context');
}
if (!store.client) {
throw new Error('client is not present in GraphQLStore');
}
// the corresponding graphql method fetcher
const method: Method = store.client.methods[methodName];
if (typeof method !== 'function') {
throw new Error(
`expected method with name "${methodName}" to be a function. found "${typeof method}"`
);
}
return { store, method };
}
const storeStateToHookState = (
state?: StoreState,
isLoadingIfNotCached?: boolean
): HookState<any, any> => {
return {
result: state ? state.context.result : undefined,
loading: state ? state.loading : !!isLoadingIfNotCached,
resolved: state ? state.resolved : false,
error:
state && state.context && state.context.errors
? state.context.errors.join('\n')
: null
};
};
type Props = {
client: GraphQLClient;
};
// extract the type from a generic: ex. T from Promise<T>
type Unpacked<T> = T extends (infer U)[]
? U
: T extends (...args: any[]) => infer U
? U
: T extends Promise<infer U>
? U
: T;
type UseClient = <
A extends { variables: Parameters<M>[0]; config?: Parameters<M>[1] }, // argsArray
K extends keyof Methods = any, // method key (name)
M extends (...args: any) => any = Methods[K], // method
R = Unpacked<ReturnType<M>>['result'] // return type without promise
>(
methodName: K,
initialFetchConfig?: {
variables: A['variables'];
config?: A['config'];
}
) => [
HookState<R, A['variables']>,
(variables: A['variables'], config?: A['config']) => Promise<Context>,
GraphQLStore
];
type HookState<T, V> = {
loading: boolean;
resolved: boolean;
context?: StoreState<T, V>['context'];
result?: StoreState<T, V>['result'];
error?: string | null;
};