Last active
October 15, 2020 13:49
-
-
Save surajp/4cbd90206203fd033a26ed3b5a157362 to your computer and use it in GitHub Desktop.
Lds Utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Reduces one or more LDS errors into a string[] of error messages. | |
* @param {FetchResponse|FetchResponse[]} errors | |
* @return {String[]} Error messages | |
*/ | |
const reduceErrors = (errors) => { | |
if (!Array.isArray(errors)) { | |
errors = [errors]; | |
} | |
return ( | |
errors | |
// Remove null/undefined items | |
.filter((error) => !!error) | |
// Extract an error message | |
.map((error) => { | |
// UI API read errors | |
if (Array.isArray(error.body)) { | |
return error.body.map((e) => e.message); | |
} | |
// UI API DML, Apex and network errors | |
else if (error.body && typeof error.body.message === "string") { | |
return error.body.message; | |
} | |
// JS errors | |
else if (typeof error.message === "string") { | |
return error.message; | |
} | |
// Unknown error shape so try HTTP status text | |
return error.statusText; | |
}) | |
// Flatten | |
.reduce((prev, curr) => prev.concat(curr), []) | |
// Remove empty strings | |
.filter((message) => !!message) | |
); | |
}; | |
const flatten = (obj, newobj, prefix) => { | |
if (!newobj) newobj = {}; | |
/*eslint-disable*/ | |
for (let prop in obj) { | |
if (!prefix) prefix = ""; | |
if (typeof obj[prop] === "object") flatten(obj[prop], newobj, prefix + prop + "_"); | |
else newobj[prefix + prop] = obj[prop]; | |
} | |
/*eslint-enable*/ | |
return newobj; | |
}; | |
const sortTableData = (data,fieldName,direction)=>{ | |
let dataCopy = JSON.parse(JSON.stringify(data)); | |
const keyValue = a=>a[fieldName]; | |
const isReverse = direction === "asc"? 1: -1; | |
dataCopy.sort((x,y)=>{ | |
const xval = keyValue(x)?keyValue(x):''; | |
const yval = keyValue(y)?keyValue(y):''; | |
return isReverse * ((xval>yval)-(yval>xval)); | |
}) | |
return dataCopy; | |
} | |
export { reduceErrors, flatten, sortTableData }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment