Skip to content

Commit

Permalink
feat: xls export -- association data shape
Browse files Browse the repository at this point in the history
  • Loading branch information
mkeen committed Jan 23, 2022
1 parent bb7d956 commit d93688f
Showing 1 changed file with 12 additions and 27 deletions.
39 changes: 12 additions & 27 deletions src/utils/xls.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,7 @@ export const createXlsFromSequelizeResults = (rows, model) => {
// Populate main sheet values
for (const [mainColName, mainCol] of columnsInMainSheet.entries()) {
if (!Object.keys(sheets).includes(model.name)) {
sheets[model.name] = {
name: model.name + 's',
data: [
columnsInMainSheet
]
}; // Column headings
sheets[model.name] = { name: model.name + 's', data: [columnsInMainSheet] }; // Column headings
}

if (!associations.map(singular => singular + 's').includes(mainColName)) {
Expand All @@ -51,48 +46,38 @@ export const createXlsFromSequelizeResults = (rows, model) => {
}
mainXlsRow.push(row[mainCol]);
}

}

if (mainXlsRow.length) {
sheets[model.name].data.push(mainXlsRow);
}


// Populate associated data sheets
for (const associatedModel of associatedModels) {
const xlsRow = [];
// Column headings for associated sheets will be available for associated sheets once its referenced by a row
if (!Object.keys(sheets).includes(associatedModel) && row[associatedModel].length > 0) {
sheets[associatedModel] = {
name: associatedModel,
data: [
columnsInResults.filter(col => !Object.keys(columnsInMainSheet).includes(col))
],
};
}

for (const [columnName, columnValue] of Object.entries(row)) {
if (!columnsInMainSheet.includes(columnName) && columnValue) {
if (columnValue && !columnsInMainSheet.includes(columnName)) {
if (Array.isArray(columnValue)) {
// one to many
for (const [_assocIndex, assocColVal] of columnValue.entries()) {
Object.values(assocColVal).map(col => xlsRow.push());
const xlsRow = [];
if (!Object.keys(sheets).includes(associatedModel)) {
sheets[associatedModel] = { name: associatedModel, data: [Object.keys(assocColVal)], };
}
Object.values(assocColVal).map(col => col === null ? 'null': col).map(col => xlsRow.push(col));
if (xlsRow.length > 0) {
sheets[associatedModel].data.push(xlsRow);
}
}
} else {
// one to one
xlsRow.push(columnValue);
}
}
if (xlsRow.length > 0) {
sheets[associatedModel].data = sheets[associatedModel].data.concat(xlsRow);
}
}
}

return sheets;
}, initialReduceValue);

console.log(JSON.stringify(Object.values(xlsData)))

return xlsx.build(Object.values(xlsData));
}

0 comments on commit d93688f

Please sign in to comment.