This repository has been archived by the owner on Jan 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.tsx
124 lines (99 loc) · 2.62 KB
/
index.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
import React, { Component } from "react";
import { DocumentNode } from "graphql";
import { ApolloError, NetworkStatus } from "apollo-client";
import { ApolloConsumer } from "react-apollo";
type QueryResult<Tdata = any> = {
data?: Tdata;
error?: ApolloError;
loading?: boolean;
networkStatus?: NetworkStatus;
};
type QueryHandlerParams = {
variables?: QueryVariables;
};
type FetchPolicy =
| "cache-first"
| "cache-and-network"
| "network-only"
| "cache-only"
| "no-cache"
| "standby";
type ErrorPolicy = "none" | "ignore" | "all";
type QueryHandler = (params?: QueryHandlerParams) => any;
type QueryRenderProp = (
result: QueryResult,
query?: QueryHandler
) => JSX.Element | any;
type SuccessHandler = (data: any) => void;
type ErrorHandler = (error: ApolloError) => void;
type QueryVariables = { [key: string]: any };
interface QueryProps {
skip?: boolean;
query: DocumentNode;
client?: any;
variables?: QueryVariables;
onError?: ErrorHandler;
onCompleted?: SuccessHandler;
errorPolicy?: ErrorPolicy;
fetchPolicy?: FetchPolicy;
children: QueryRenderProp;
fetchOnMount?: boolean;
}
const INITIAL_STATE: QueryResult = {
data: undefined,
error: undefined,
loading: undefined,
networkStatus: undefined
};
class QueryRequest extends Component<QueryProps> {
state: QueryResult = INITIAL_STATE;
request = async (params?: QueryHandlerParams) => {
const {
skip,
query,
client,
variables,
onError,
onCompleted,
errorPolicy,
fetchPolicy
} = this.props;
if (skip || !client) return;
try {
this.setState(() => ({ ...INITIAL_STATE, loading: true }));
const response = await client.query({
query,
fetchPolicy,
errorPolicy,
variables: variables ? variables : params ? params.variables : {}
});
this.setState(
() => ({ ...INITIAL_STATE, ...response }),
() => onCompleted && onCompleted(response ? response.data : {})
);
return response;
} catch (error) {
this.setState(
() => ({ ...INITIAL_STATE, error, loading: false }),
() => onError && onError(error)
);
}
};
componentDidMount() {
const { children, fetchOnMount } = this.props;
if (fetchOnMount || children.length <= 1) {
this.request();
}
}
render() {
const { props, request, state } = this;
const { children: render } = props;
return render(state, request);
}
}
export const Query = (props: QueryProps) => (
<ApolloConsumer>
{client => <QueryRequest client={client} {...props} />}
</ApolloConsumer>
);
export default Query;