forked from RedHatInsights/curiosity-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreduxHelpers.js
More file actions
467 lines (403 loc) · 12.4 KB
/
Copy pathreduxHelpers.js
File metadata and controls
467 lines (403 loc) · 12.4 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import _get from 'lodash/get';
import _isPlainObject from 'lodash/isPlainObject';
import _camelCase from 'lodash/camelCase';
import _snakeCase from 'lodash/snakeCase';
import { helpers } from '../../common';
/**
* @memberof Helpers
* @module ReduxHelpers
*/
/**
* Apply a "fulfilled" suffix for Redux Promise Middleware action responses.
*
* @param {string} base
* @returns {string}
*/
const FULFILLED_ACTION = (base = '') => `${base}_FULFILLED`;
/**
* Apply a "pending" suffix for Redux Promise Middleware action responses.
*
* @param {string} base
* @returns {string}
*/
const PENDING_ACTION = (base = '') => `${base}_PENDING`;
/**
* Apply a "rejected" suffix for Redux Promise Middleware action responses.
*
* @param {string} base
* @returns {string}
*/
const REJECTED_ACTION = (base = '') => `${base}_REJECTED`;
/**
* Apply a "status range" suffix for Status Middleware action responses.
*
* @param {string} status
* @returns {string}
*/
const HTTP_STATUS_RANGE = status => `${status}_STATUS_RANGE`;
/**
* Set an API query based on specific API "acceptable values" schema.
*
* @param {object} values
* @param {object} schema
* @param {*} [initialValue]
* @returns {object}
*/
const setApiQuery = (values, schema, initialValue) => {
const generated = {};
const schemaArr = (schema && Object.values(schema)) || [];
schemaArr.forEach(value => {
if (initialValue === undefined) {
if (value in values) {
generated[value] = values?.[value];
}
} else {
generated[value] = values?.[value] || initialValue;
}
});
return generated;
};
// ToDo: research applying a maintained schema map/normalizer such as, normalizr
/**
* Apply a set of schemas using either an array of objects in the
* form of [{ madeUpKey: 'some_api_key' }], or an array of arrays
* in the form of [['some_api_key','another_api_key']]
*
* @param {Array} schemas
* @param {*} [initialValue]
* @returns {Array}
*/
const setResponseSchemas = (schemas = [], initialValue) =>
schemas.map(schema => {
const generated = {};
const arr = (Array.isArray(schema) && schema) || Object.values(schema);
arr.forEach(value => {
generated[value] = initialValue;
});
return generated;
});
/**
* Normalize an API response.
*
* @param {*} responses
* @param {object} responses.response
* @param {object} responses.response.schema
* @param {Array|object} responses.response.data
* @param {string} responses.response.keyCase
* @param {Function} responses.response.customResponseEntry
* @param {Function} responses.response.customResponseValue
* @param {string} responses.response.keyPrefix
* @returns {Array}
*/
const setNormalizedResponse = (...responses) => {
const parsedResponses = [];
responses.forEach(
({ schema = {}, data, customResponseEntry, customResponseValue, keyPrefix: prefix, keyCase = 'camel' }) => {
const isArray = Array.isArray(data);
const updatedData = (isArray && data) || (data && [data]) || [];
const [generatedSchema = {}] = setResponseSchemas([schema]);
const parsedResponse = [];
updatedData.forEach((value, index) => {
const generateReflectedData = ({
dataObj,
keyPrefix = '',
keyCaseType,
customEntry,
customValue = null,
update = helpers.noop
}) => {
let updatedDataObj = {};
Object.entries(dataObj).forEach(([dataObjKey, dataObjValue]) => {
let casedDataObjKey;
switch (keyCaseType) {
case 'camel':
casedDataObjKey = _camelCase(`${keyPrefix} ${dataObjKey}`).trim();
break;
case 'snake':
casedDataObjKey = _snakeCase(`${keyPrefix} ${dataObjKey}`).trim();
break;
case 'default':
default:
casedDataObjKey = `${dataObjKey}`.trim();
break;
}
let val = dataObjValue;
if (typeof val === 'number') {
val = (Number.isInteger(val) && Number.parseInt(val, 10)) || Number.parseFloat(val) || val;
}
if (typeof customValue === 'function') {
updatedDataObj[casedDataObjKey] = customValue({ data: dataObj, key: dataObjKey, value: val, index });
} else {
updatedDataObj[casedDataObjKey] = val;
}
});
if (typeof customEntry === 'function') {
updatedDataObj = customEntry(updatedDataObj, index);
}
update(updatedDataObj);
};
generateReflectedData({
keyPrefix: prefix,
dataObj: { ...generatedSchema, ...value },
keyCaseType: keyCase,
customEntry: customResponseEntry,
customValue: customResponseValue,
update: generatedData => parsedResponse.push(generatedData)
});
});
parsedResponses.push(parsedResponse);
}
);
return parsedResponses;
};
/**
* Create a single response from an array of service call responses.
* Aids in handling a Promise.all response.
*
* @param {Array|object} results
* @returns {object}
*/
const getSingleResponseFromResultArray = results => {
const updatedResults =
(results.payload && results.payload.response) || results.payload || results.response || results;
const updatedResultsMessage =
(results.payload && results.payload.message && { message: results.payload.message }) ||
(results.message && { message: results.message });
if (Array.isArray(updatedResults)) {
const firstErrorResponse = updatedResults.find(value => _get(value, 'response.status', value.status) >= 300);
const firstSuccessResponse = updatedResults.find(value => _get(value, 'response.status', value.status) < 300);
return (
(firstErrorResponse && { ...firstErrorResponse, ...updatedResultsMessage }) ||
(firstSuccessResponse && { ...firstSuccessResponse, ...updatedResultsMessage })
);
}
return { ...updatedResults, ...updatedResultsMessage };
};
/**
* Get a http status message from a service call.
*
* @param {Array|object} results
* @returns {string|null|*}
*/
const getMessageFromResults = results => {
const updatedResults = getSingleResponseFromResultArray(results);
if (helpers.isPromise(updatedResults)) {
return null;
}
const status = updatedResults.status || 0;
const statusResponse = updatedResults.statusText || '';
const messageResponse = updatedResults.message;
const dataResponse = updatedResults.data || null;
const formattedStatus = (status && `${status} `) || '';
if (messageResponse && typeof messageResponse === 'string') {
return messageResponse.trim();
}
if (dataResponse && typeof dataResponse === 'string') {
return `${formattedStatus}${dataResponse}`.trim();
}
if (status >= 400 && _isPlainObject(dataResponse)) {
return `${formattedStatus}${JSON.stringify(dataResponse)}`;
}
return (statusResponse && statusResponse.trim()) || null;
};
/**
* Get a date string from a service call.
*
* @param {Array|object} results
* @returns {null|string|Date}
*/
const getDateFromResults = results => {
const updatedResults = getSingleResponseFromResultArray(results);
if (helpers.isPromise(updatedResults)) {
return null;
}
return _get(updatedResults, 'headers.date', null);
};
/**
* Get a http status from a service call response.
*
* @param {Array|object} results
* @returns {number}
*/
const getStatusFromResults = results => {
const updatedResults = getSingleResponseFromResultArray(results);
if (helpers.isPromise(updatedResults)) {
return 0;
}
return updatedResults?.status || 0;
};
/**
* Convenience method for setting object properties, specifically Redux reducer based state objects.
*
* @param {string} prop
* @param {object} data
* @param {object} options
* @param {object} options.state
* @param {object} options.initialState
* @param {boolean} options.reset
* @returns {object}
*/
const setStateProp = (prop, data, options) => {
const { state = {}, initialState = {}, reset = true } = options;
let obj = { ...state };
if (helpers.DEV_MODE && prop && !state[prop]) {
console.error(`Error: Property ${prop} does not exist within the passed state.`, state);
}
if (helpers.DEV_MODE && reset && prop && !initialState[prop]) {
console.warn(`Warning: Property ${prop} does not exist within the passed initialState.`, initialState);
}
if (reset && prop) {
obj[prop] = {
...state[prop],
...initialState[prop],
...data
};
} else if (reset && !prop) {
obj = {
...state,
...initialState,
...data
};
} else if (prop) {
obj[prop] = {
...state[prop],
...data
};
} else {
obj = {
...state,
...data
};
}
return obj;
};
/**
* Retrieve a data property either from an array of responses, or a single response.
*
* @param {Array|object} results
* @returns {Array|object}
*/
const singlePromiseDataResponseFromArray = results => {
const updatedResults =
(results.payload && results.payload.response) || results.payload || results.response || results;
if (Array.isArray(updatedResults)) {
return updatedResults.map(value => value.data || {});
}
return updatedResults.data || {};
};
/**
* Alias for singlePromiseDataResponseFromArray.
*
* @param {Array|object} results
* @returns {Array|object}
*/
const getDataFromResults = results => singlePromiseDataResponseFromArray(results);
/**
* Automatically apply reducer logic to state by handling promise responses from redux-promise-middleware.
*
* @param {Array} types
* @param {object} state
* @param {object} action
* @property { string } type
* @returns {object}
*/
const generatedPromiseActionReducer = (types = [], state = {}, action = {}) => {
const { type } = action;
const expandedTypes = [];
types.forEach(
val =>
(Array.isArray(val.type) && val.type.forEach(subVal => expandedTypes.push({ ref: val.ref, type: subVal }))) ||
expandedTypes.push(val)
);
const [whichType] = expandedTypes.filter(val =>
new RegExp(
`^(${REJECTED_ACTION(val.type || val)}|${PENDING_ACTION(val.type || val)}|${FULFILLED_ACTION(val.type || val)})$`
).test(type)
);
if (!whichType) {
return state;
}
const expandMetaTypes = (meta = {}) => {
const updatedMeta = { ...meta };
return {
meta: { ...updatedMeta },
...Object.fromEntries(Object.entries(meta).map(([key, value]) => [_camelCase(`meta ${key}`), value]))
};
};
const baseState = {
error: false,
errorMessage: '',
fulfilled: false,
pending: false,
...expandMetaTypes(action.meta)
};
// Automatically apply data and state to a contextual ID if meta.id exists.
const setId = data =>
(typeof action.meta?.id === 'string' && action.meta?.id && { [action.meta.id]: { ...baseState, ...data } }) || {
...baseState,
...data
};
switch (type) {
case REJECTED_ACTION(whichType.type || whichType):
const errorMessage = getMessageFromResults(action);
let errorResponse;
if (errorMessage === 'cancelled request') {
errorResponse = {
date: getDateFromResults(action),
cancelled: true
};
} else {
errorResponse = {
error: true,
errorMessage,
status: getStatusFromResults(action)
};
}
return setStateProp(whichType.ref || null, setId(errorResponse), {
state
});
case PENDING_ACTION(whichType.type || whichType):
return setStateProp(
whichType.ref || null,
setId({
pending: true
}),
{
state
}
);
case FULFILLED_ACTION(whichType.type || whichType):
return setStateProp(
whichType.ref || null,
setId({
date: getDateFromResults(action),
data: singlePromiseDataResponseFromArray(action),
fulfilled: true,
status: getStatusFromResults(action)
}),
{
state
}
);
default:
return state;
}
};
const reduxHelpers = {
FULFILLED_ACTION,
PENDING_ACTION,
REJECTED_ACTION,
HTTP_STATUS_RANGE,
setApiQuery,
setResponseSchemas,
setNormalizedResponse,
generatedPromiseActionReducer,
getDataFromResults,
getDateFromResults,
getMessageFromResults,
getSingleResponseFromResultArray,
getStatusFromResults,
setStateProp,
singlePromiseDataResponseFromArray
};
export { reduxHelpers as default, reduxHelpers };