forked from contiamo/restful-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet.tsx
271 lines (243 loc) · 7.25 KB
/
Get.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
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
import { DebounceSettings } from "lodash";
import debounce from "lodash/debounce";
import * as React from "react";
import url from "url";
import RestfulReactProvider, { InjectedProps, RestfulReactConsumer, RestfulReactProviderProps } from "./Context";
import { processResponse } from "./util/processResponse";
/**
* A function that resolves returned data from
* a fetch call.
*/
export type ResolveFunction<T> = (data: any) => T;
export interface GetDataError<TError> {
message: string;
data: TError | string;
}
/**
* An enumeration of states that a fetchable
* view could possibly have.
*/
export interface States<TData, TError> {
/** Is our view currently loading? */
loading: boolean;
/** Do we have an error in the view? */
error?: GetState<TData, TError>["error"];
}
/**
* An interface of actions that can be performed
* within Get
*/
export interface Actions<TData> {
/** Refetches the same path */
refetch: () => Promise<TData | null>;
}
/**
* Meta information returned to the fetchable
* view.
*/
export interface Meta {
/** The entire response object passed back from the request. */
response: Response | null;
/** The absolute path of this request. */
absolutePath: string;
}
/**
* Props for the <Get /> component.
*/
export interface GetProps<TData, TError> {
/**
* The path at which to request data,
* typically composed by parent Gets or the RestfulProvider.
*/
path: string;
/**
* A function that recieves the returned, resolved
* data.
*
* @param data - data returned from the request.
* @param actions - a key/value map of HTTP verbs, aliasing destroy to DELETE.
*/
children: (data: TData | null, states: States<TData, TError>, actions: Actions<TData>, meta: Meta) => React.ReactNode;
/** Options passed into the fetch call. */
requestOptions?: RestfulReactProviderProps["requestOptions"];
/**
* Don't send the error to the Provider
*/
localErrorOnly?: boolean;
/**
* A function to resolve data return from the backend, most typically
* used when the backend response needs to be adapted in some way.
*/
resolve?: ResolveFunction<TData>;
/**
* Should we wait until we have data before rendering?
* This is useful in cases where data is available too quickly
* to display a spinner or some type of loading state.
*/
wait?: boolean;
/**
* Should we fetch data at a later stage?
*/
lazy?: boolean;
/**
* An escape hatch and an alternative to `path` when you'd like
* to fetch from an entirely different URL.
*
*/
base?: string;
/**
* How long do we wait between subsequent requests?
* Uses [lodash's debounce](https://lodash.com/docs/4.17.10#debounce) under the hood.
*/
debounce?:
| {
wait?: number;
options: DebounceSettings;
}
| boolean
| number;
}
/**
* State for the <Get /> component. These
* are implementation details and should be
* hidden from any consumers.
*/
export interface GetState<TData, TError> {
data: TData | null;
response: Response | null;
error: GetDataError<TError> | null;
loading: boolean;
}
/**
* The <Get /> component without Context. This
* is a named class because it is useful in
* debugging.
*/
class ContextlessGet<TData, TError> extends React.Component<
GetProps<TData, TError> & InjectedProps,
Readonly<GetState<TData, TError>>
> {
constructor(props: GetProps<TData, TError> & InjectedProps) {
super(props);
if (typeof props.debounce === "object") {
this.fetch = debounce(this.fetch, props.debounce.wait, props.debounce.options);
} else if (typeof props.debounce === "number") {
this.fetch = debounce(this.fetch, props.debounce);
} else if (props.debounce) {
this.fetch = debounce(this.fetch);
}
}
public readonly state: Readonly<GetState<TData, TError>> = {
data: null, // Means we don't _yet_ have data.
response: null,
loading: !this.props.lazy,
error: null,
};
public static defaultProps = {
base: "",
resolve: (unresolvedData: any) => unresolvedData,
};
public componentDidMount() {
if (!this.props.lazy) {
this.fetch();
}
}
public componentDidUpdate(prevProps: GetProps<TData, TError>) {
// If the path or base prop changes, refetch!
const { path, base } = this.props;
if (prevProps.path !== path || prevProps.base !== base) {
if (!this.props.lazy) {
this.fetch();
}
}
}
public getRequestOptions = (
extraOptions?: Partial<RequestInit>,
extraHeaders?: boolean | { [key: string]: string },
) => {
const { requestOptions } = this.props;
if (typeof requestOptions === "function") {
return {
...extraOptions,
...requestOptions(),
headers: new Headers({
...(typeof extraHeaders !== "boolean" ? extraHeaders : {}),
...(extraOptions || {}).headers,
...(requestOptions() || {}).headers,
}),
};
}
return {
...extraOptions,
...requestOptions,
headers: new Headers({
...(typeof extraHeaders !== "boolean" ? extraHeaders : {}),
...(extraOptions || {}).headers,
...(requestOptions || {}).headers,
}),
};
};
public fetch = async (requestPath?: string, thisRequestOptions?: RequestInit) => {
const { base, path, resolve } = this.props;
if (this.state.error || !this.state.loading) {
this.setState(() => ({ error: null, loading: true }));
}
const request = new Request(
url.resolve(base!, requestPath || path || ""),
this.getRequestOptions(thisRequestOptions),
);
const response = await fetch(request);
const { data, responseError } = await processResponse(response);
if (!response.ok || responseError) {
const error = {
message: `Failed to fetch: ${response.status} ${response.statusText}${responseError ? " - " + data : ""}`,
data,
};
this.setState({
loading: false,
error,
});
if (!this.props.localErrorOnly && this.props.onError) {
this.props.onError(error, () => this.fetch(requestPath, thisRequestOptions));
}
return null;
}
this.setState({ loading: false, data: resolve!(data) });
return data;
};
public render() {
const { children, wait, path, base } = this.props;
const { data, error, loading, response } = this.state;
if (wait && data === null) {
return <></>; // Show nothing until we have data.
}
return children(
data,
{ loading, error },
{ refetch: this.fetch },
{ response, absolutePath: url.resolve(base!, path) },
);
}
}
/**
* The <Get /> component _with_ context.
* Context is used to compose path props,
* and to maintain the base property against
* which all requests will be made.
*
* We compose Consumers immediately with providers
* in order to provide new `base` props that contain
* a segment of the path, creating composable URLs.
*/
function Get<TData = any, TError = any>(props: GetProps<TData, TError>) {
return (
<RestfulReactConsumer>
{contextProps => (
<RestfulReactProvider {...contextProps} base={url.resolve(contextProps.base, props.path)}>
<ContextlessGet {...contextProps} {...props} />
</RestfulReactProvider>
)}
</RestfulReactConsumer>
);
}
export default Get;