2018-03-22 16:43:35 +01:00
|
|
|
// JSON parser
|
|
|
|
const parseJson = (data, filters = []) => {
|
|
|
|
const list = data.map(item => {
|
|
|
|
const temp = {};
|
|
|
|
// Apply filters
|
|
|
|
Object.entries(item).forEach(([key, value]) => {
|
|
|
|
if (!filters.includes(key)) temp[key] = value;
|
|
|
|
});
|
|
|
|
return temp;
|
|
|
|
});
|
|
|
|
// Beautify JSON
|
|
|
|
return JSON.stringify(list, null, '\t');
|
|
|
|
};
|
2018-02-23 22:25:25 +01:00
|
|
|
|
2018-03-22 16:43:35 +01:00
|
|
|
// CSV Parser
|
2018-02-23 22:25:25 +01:00
|
|
|
// No need for an external module:
|
|
|
|
// https://gist.github.com/btzr-io/55c3450ea3d709fc57540e762899fb85
|
2018-03-22 16:43:35 +01:00
|
|
|
const parseCsv = (data, filters = []) => {
|
2018-02-23 22:25:25 +01:00
|
|
|
// Get items for header
|
2018-03-22 16:43:35 +01:00
|
|
|
const getHeaders = item => {
|
|
|
|
const list = [];
|
|
|
|
// Apply filters
|
|
|
|
Object.entries(item).forEach(([key]) => {
|
|
|
|
if (!filters.includes(key)) list.push(key);
|
|
|
|
});
|
|
|
|
// return headers
|
|
|
|
return list.join(',');
|
|
|
|
};
|
|
|
|
|
2018-02-23 22:25:25 +01:00
|
|
|
// Get rows content
|
|
|
|
const getData = list =>
|
|
|
|
list
|
|
|
|
.map(item => {
|
2018-03-22 16:43:35 +01:00
|
|
|
const row = [];
|
|
|
|
// Apply filters
|
|
|
|
Object.entries(item).forEach(([key, value]) => {
|
|
|
|
if (!filters.includes(key)) row.push(value);
|
|
|
|
});
|
|
|
|
// return rows
|
|
|
|
return row.join(',');
|
2018-02-23 22:25:25 +01:00
|
|
|
})
|
|
|
|
.join('\n');
|
2018-03-22 16:43:35 +01:00
|
|
|
|
2018-02-23 22:25:25 +01:00
|
|
|
// Return CSV string
|
|
|
|
return `${getHeaders(data[0])} \n ${getData(data)}`;
|
|
|
|
};
|
|
|
|
|
2018-03-22 16:43:35 +01:00
|
|
|
const parseData = (data, format, filters = []) => {
|
2018-02-23 22:25:25 +01:00
|
|
|
// Check for validation
|
2018-02-24 01:24:00 +01:00
|
|
|
const valid = data && data[0] && format;
|
2018-02-23 22:25:25 +01:00
|
|
|
// Pick a format
|
|
|
|
const formats = {
|
2018-03-22 16:43:35 +01:00
|
|
|
csv: list => parseCsv(list, filters),
|
|
|
|
json: list => parseJson(list, filters),
|
2018-02-23 22:25:25 +01:00
|
|
|
};
|
2018-03-22 16:43:35 +01:00
|
|
|
|
2018-02-23 22:25:25 +01:00
|
|
|
// Return parsed data: JSON || CSV
|
|
|
|
return valid && formats[format] ? formats[format](data) : undefined;
|
2018-02-24 01:24:00 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
export default parseData;
|