forked from joehoyle/with-api-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
254 lines (232 loc) · 5.85 KB
/
index.js
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
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { isEqual } from 'lodash';
class ApiCache {
constructor( fetch ) {
this.fetch = fetch;
this.cache = {};
this.eventSubscribers = {};
}
get( url, params ) {
const promise = this.fetch( url, params )
.then( r => this.handleResponse( r ) )
.then( response => {
this.setCache( url, response )
this.trigger( url, response )
} )
.catch( error => {
this.setCache( url, error )
this.trigger( url, error )
} )
this.setCache( url, 'pending' )
return promise;
}
getCache( url ) {
return this.cache[ url ];
}
setCache( url, response ) {
this.cache[ url ] = response;
}
handleResponse( response ) {
return response.text().then( responseText => {
try {
var json = JSON.parse( responseText )
} catch ( e ) {
throw new Error( responseText );
}
if ( response.status > 299 ) {
throw new Error( json.message );
}
return json;
} )
}
on( url, callback ) {
this.eventSubscribers[ url ] = this.eventSubscribers[ url ] || [];
this.eventSubscribers[ url ].push( callback );
if ( this.getCache( url ) === 'pending' ) {
return;
}
if ( this.getCache( url ) ) {
return callback( this.getCache( url ) );
}
this.get( url )
}
trigger( url, response ) {
if ( ! this.eventSubscribers[url] ) {
console.log( 'no subscribers found for url', url )
}
this.eventSubscribers[url].map( f => f( response ) )
}
removeCache( url ) {
delete this.cache[ url ];
}
}
export class Provider extends Component {
static childContextTypes = {
api: PropTypes.func.isRequired,
apiCache: PropTypes.object.isRequired,
};
constructor( props ) {
super( props )
this.apiCache = new ApiCache( props.fetch );
}
getChildContext() {
return { api: this.props.fetch, apiCache: this.apiCache };
}
render() {
return this.props.children;
}
}
export const withApiData = mapPropsToData => WrappedComponent => {
class APIDataComponent extends Component {
static contextTypes = {
api: PropTypes.func.isRequired,
apiCache: PropTypes.object.isRequired,
};
constructor( props ) {
super( props );
const dataMap = mapPropsToData( this.props );
const keys = Object.keys( dataMap );
const dataProps = {};
keys.forEach( key => {
dataProps[ key ] = {
isLoading: true,
error: null,
data: null,
}
} );
this.state = dataProps;
}
componentDidMount() {
this.unmounted = false;
this.updateProps( this.props );
}
componentWillUnmount() {
this.unmounted = true;
}
componentWillReceiveProps( nextProps ) {
const oldDataMap = mapPropsToData( this.props );
const newDataMap = mapPropsToData( nextProps );
if ( isEqual( oldDataMap, newDataMap ) ) {
return;
}
// When the `mapPropsToData` function returns a different
// result, reset all the data to empty and loading.
const keys = Object.keys( newDataMap );
const dataProps = {};
keys.forEach( key => {
dataProps[ key ] = {
isLoading: true,
error: null,
data: null,
}
} );
this.setState( dataProps, () => this.updateProps( nextProps ) );
}
updateProps( props ) {
const dataMap = mapPropsToData( props );
Object.entries( dataMap ).forEach( ( [ key, endpoint ] ) => {
if ( ! endpoint ) {
return;
}
this.setState( {
[ key ]: {
isLoading: true,
error: null,
...this.state[ key ],
},
} )
this.context.apiCache.on( endpoint, data => {
let error = null;
if ( this.unmounted ) {
return data;
}
if ( data instanceof Error ) {
error = data;
data = null;
}
const prop = {
error,
isLoading: false,
data,
};
this.setState( { [ key ]: prop } );
} )
} );
}
onFetch( ...args ) {
return this.context.api( ...args );
}
onRefreshData() {
this.onInvalidateData();
}
onInvalidateData() {
const dataMap = mapPropsToData( this.props );
Object.entries( dataMap ).forEach( ( [ key, endpoint ] ) => {
this.context.apiCache.removeCache( endpoint )
} );
this.updateProps( this.props );
}
onInvalidateDataForUrl( url ) {
this.context.apiCache.removeCache( url )
this.updateProps( this.props );
this.context.apiCache.get( url );
}
onPost( url, data ) {
return this.onFetch( url, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify( data ),
method: 'POST',
} ).then( response => {
return response.text().then( responseText => {
try {
var json = JSON.parse( responseText )
} catch( e ) {
throw new Error( responseText );
}
return json;
} )
} )
}
getWrappedInstance() {
return this.wrapperRef;
}
render() {
return (
<WrappedComponent
{ ...this.props }
{ ...this.state }
fetch={( ...args ) => this.onFetch( ...args )}
post={ (...args) => this.onPost(...args)}
ref={ref => this.wrapperRef = ref}
refreshData={ ( ...args ) => this.onRefreshData( ...args ) }
invalidateData={ () => this.onInvalidateData() }
invalidateDataForUrl={ ( ...args ) => this.onInvalidateDataForUrl( ...args ) }
/>
);
}
}
// Derive display name from original component
const { displayName = WrappedComponent.name || 'Component' } = WrappedComponent;
APIDataComponent.displayName = `apiData(${ displayName })`;
return APIDataComponent;
}
export class WithApiData extends Component {
render( props ) {
const ChildComponent = withApiData( this.props.mapPropsToData )( this.props.render || this.props.component );
return <ChildComponent ref={ apiData => this.apiData = apiData } {...this.props} />
}
refreshData() {
if ( this.apiData ) {
this.apiData.onRefreshData();
}
}
invalidateData() {
if ( this.apiData ) {
this.apiData.onInvalidateData();
}
}
}