-
Notifications
You must be signed in to change notification settings - Fork 478
Expand file tree
/
Copy pathReactiveBase.js
More file actions
346 lines (314 loc) · 9.82 KB
/
Copy pathReactiveBase.js
File metadata and controls
346 lines (314 loc) · 9.82 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/* eslint-disable global-require */
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import Appbase from 'appbase-js';
import AppbaseAnalytics from '@appbaseio/analytics';
import 'url-search-params-polyfill';
import { ThemeProvider } from 'emotion-theming';
import configureStore from '@appbaseio/reactivecore';
import {
checkSomePropChange,
transformRequestUsingEndpoint,
} from '@appbaseio/reactivecore/lib/utils/helper';
import { updateAnalyticsConfig } from '@appbaseio/reactivecore/lib/actions/analytics';
import { setValues } from '@appbaseio/reactivecore/lib/actions/value';
import types from '@appbaseio/reactivecore/lib/utils/types';
import URLParamsProvider from './URLParamsProvider';
import getTheme from '../../styles/theme';
import {
composeThemeObject,
ReactReduxContext,
SearchPreferencesContext,
ReduxGetStateContext,
X_SEARCH_CLIENT,
} from '../../utils';
class ReactiveBase extends Component {
constructor(props) {
super(props);
this.state = {
key: '__REACTIVE_BASE__',
};
this.setStore(props);
}
componentDidUpdate(prevProps) {
checkSomePropChange(
this.props,
prevProps,
[
'app',
'url',
'type',
'credentials',
'mapKey',
'mapLibraries',
'headers',
'graphQLUrl',
],
() => {
this.setStore(this.props);
this.setState((state) => ({
key: `${state.key}-0`,
}));
},
);
checkSomePropChange(this.props, prevProps, ['reactivesearchAPIConfig'], () => {
if (this.store) {
this.store.dispatch(updateAnalyticsConfig(this.props.reactivesearchAPIConfig));
}
});
}
componentDidCatch(error, errorInfo) {
console.error(
"An error has occured. You're using Reactivesearch Version:",
`${process.env.VERSION || require('../../../package.json').version}.`,
'If you think this is a problem with Reactivesearch, please try updating',
"to the latest version. If you're already at the latest version, please open",
'an issue at https://github.com/appbaseio/reactivesearch/issues',
error,
errorInfo,
);
}
get headers() {
const { headers, reactivesearchAPIConfig, mongodb, endpoint } = this.props;
const { enableTelemetry } = reactivesearchAPIConfig || {};
return {
...(!mongodb && {
'X-Search-Client': X_SEARCH_CLIENT,
...(enableTelemetry === false && { 'X-Enable-Telemetry': false }),
}),
...headers,
...(endpoint &&
endpoint.headers && {
...endpoint.headers,
}),
};
}
setStore = (props) => {
this.type = props.type ? props.type : '*';
const credentials =
props.url && props.url.trim() !== '' && !props.credentials ? null : props.credentials;
let url = props.url && props.url.trim() !== '' ? props.url : '';
if (props.endpoint instanceof Object) {
if (props.endpoint.url) {
url = props.endpoint.url;
} else {
throw Error(
'Error(ReactiveSearch): The `endpoint` prop object requires `url` property.',
);
}
}
const config = {
url,
app: props.app,
credentials,
type: this.type,
transformRequest: props.transformRequest,
analytics: props.reactivesearchAPIConfig
? props.reactivesearchAPIConfig.recordAnalytics
: true,
analyticsConfig: props.reactivesearchAPIConfig,
graphQLUrl: props.graphQLUrl,
transformResponse: props.transformResponse,
mongodb: props.mongodb,
...(props.endpoint instanceof Object && { endpoint: props.endpoint }),
httpRequestTimeout: props.httpRequestTimeout * 1000,
};
let queryParams = '';
if (typeof window !== 'undefined') {
queryParams = props.getSearchParams ? props.getSearchParams() : window.location.search;
} else {
queryParams = props.queryParams || '';
}
const params = new URLSearchParams(queryParams);
let selectedValues = {};
let urlValues = {};
const isValidURLValue = (value) => {
if (value === null || value === undefined) return false;
const type = typeof value;
if (type === 'string' || type === 'number' || type === 'boolean') return true;
if (Array.isArray(value)) {
return value.every((item) => {
const itemType = typeof item;
return itemType === 'string' || itemType === 'number' || itemType === 'boolean';
});
}
if (type === 'object' && value.constructor === Object) {
return Object.values(value).every((item) => {
const itemType = typeof item;
return itemType === 'string' || itemType === 'number' || itemType === 'boolean' || item === null;
});
}
return false;
};
const isValidParsedParam = (parsedParams) => {
if (parsedParams === null || parsedParams === undefined) return false;
const type = typeof parsedParams;
if (type === 'string' || type === 'number' || type === 'boolean' || Array.isArray(parsedParams)) {
return true;
}
if (type === 'object' && parsedParams.constructor === Object) {
if (Object.prototype.hasOwnProperty.call(parsedParams, 'value')) {
return isValidURLValue(parsedParams.value);
}
return isValidURLValue(parsedParams);
}
return false;
};
Array.from(params.keys()).forEach((key) => {
try {
const parsedParams = JSON.parse(params.get(key));
if (!isValidParsedParam(parsedParams)) {
return;
}
const selectedValue = {};
if (parsedParams && typeof parsedParams === 'object' && Object.prototype.hasOwnProperty.call(parsedParams, 'value')) {
selectedValue.value = parsedParams.value;
} else {
selectedValue.value = parsedParams;
}
if (parsedParams && parsedParams.category && typeof parsedParams.category === 'string') {
selectedValue.category = parsedParams.category;
}
selectedValue.reference = 'URL';
selectedValues = {
...selectedValues,
[key]: selectedValue,
};
urlValues = {
...urlValues,
[key]: selectedValue.value,
};
} catch (e) {
// Do not add to selectedValues if JSON parsing fails.
}
});
const { themePreset, endpoint, reactivesearchAPIConfig } = props;
const appbaseRef = Appbase(config);
appbaseRef.transformRequest = (request) => {
const modifiedRequest = transformRequestUsingEndpoint(request, endpoint);
if (this.props.transformRequest) return this.props.transformRequest(modifiedRequest);
return modifiedRequest;
};
const analyticsInitConfig = {
url: url && url.replace(/\/\/.*@/, '//'),
credentials: appbaseRef.credentials,
// When endpoint prop is used index is not defined, so we use _default
index: appbaseRef.app || '_default',
globalCustomEvents: reactivesearchAPIConfig && reactivesearchAPIConfig.customEvents,
};
try {
if (this.props.endpoint && this.props.endpoint.url) {
// Remove parts between '//' and first '/' in the url
analyticsInitConfig.url = this.props.endpoint.url.replace(/\/\/(.*?)\/.*/, '//$1');
const headerCredentials =
this.props.endpoint.headers && this.props.endpoint.headers.Authorization;
analyticsInitConfig.credentials =
headerCredentials && headerCredentials.replace('Basic ', '');
// Decode the credentials
analyticsInitConfig.credentials =
analyticsInitConfig.credentials && atob(analyticsInitConfig.credentials);
}
} catch (e) {
console.error('Endpoint not set correctly for analytics');
console.error(e);
}
let analyticsRef;
if (config.analytics) {
analyticsRef = AppbaseAnalytics.init(analyticsInitConfig);
}
const initialState = {
config: {
...config,
mapKey: props.mapKey,
mapLibraries: props.mapLibraries,
themePreset,
initialQueriesSyncTime: props.initialQueriesSyncTime,
initialTimestamp: new Date().getTime(),
},
appbaseRef,
analyticsRef,
selectedValues,
urlValues,
headers: this.headers,
...this.props.initialState,
};
this.store = configureStore(initialState);
// server side rendered app to collect context
if (
typeof window === 'undefined' &&
props.contextCollector &&
!this.calledContextCollector
) {
this.calledContextCollector = true;
const res = props.contextCollector({
ctx: this.store,
});
// necessary for supporting SSR of queryParams
this.store.dispatch(setValues(res.selectedValues));
}
};
getReduxState = () => this.store.getState();
render() {
const theme = composeThemeObject(getTheme(this.props.themePreset), this.props.theme);
return (
<SearchPreferencesContext.Provider value={this.props.preferences}>
<ThemeProvider theme={theme} key={this.state.key}>
<Provider context={ReactReduxContext} store={this.store}>
<URLParamsProvider
headers={this.headers}
style={this.props.style}
as={this.props.as}
className={this.props.className}
getSearchParams={this.props.getSearchParams}
setSearchParams={this.props.setSearchParams}
>
<ReduxGetStateContext.Provider value={this.getReduxState}>
{this.props.children}
</ReduxGetStateContext.Provider>
</URLParamsProvider>
</Provider>
</ThemeProvider>
</SearchPreferencesContext.Provider>
);
}
}
ReactiveBase.defaultProps = {
theme: {},
themePreset: 'light',
initialState: {},
graphQLUrl: '',
as: 'div',
endpoint: null,
httpRequestTimeout: 30,
};
ReactiveBase.propTypes = {
app: types.string,
as: types.string,
children: types.children,
credentials: types.string,
headers: types.headers,
queryParams: types.string,
theme: types.style,
themePreset: types.themePreset,
type: types.string,
url: types.string,
transformRequest: types.func,
initialQueriesSyncTime: types.number,
mapKey: types.string,
mapLibraries: types.stringArray,
style: types.style,
className: types.string,
initialState: types.children,
analytics: types.bool,
reactivesearchAPIConfig: types.appbaseConfig,
graphQLUrl: types.string,
transformResponse: types.func,
getSearchParams: types.func,
setSearchParams: types.func,
mongodb: types.mongodb,
preferences: types.preferences,
endpoint: types.endpoint,
contextCollector: types.func,
httpRequestTimeout: types.number,
};
export default ReactiveBase;