Skip to content

Commit

Permalink
fix sanitisation of the csv content
Browse files Browse the repository at this point in the history
  • Loading branch information
imperosol committed Dec 18, 2024
1 parent 1ba5096 commit 0ee1887
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions core/static/bundled/utils/csv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,32 @@ function getNested<T extends object>(obj: T, key: NestedKeyOf<T>) {
return res;
}


/**
* Convert the content the string to make sure it won't break
* the resulting csv.
* cf. https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules
*/
function sanitiseCell(content: string): string {
return `"${content.replace(/"/g, '""')}"`;
}

export const csv = {
stringify: <T extends object>(objs: T[], options?: StringifyOptions<T>) => {
const columns = options.columns;
const content = objs
.map((obj) => {
return columns
.map((col) => {
return (getNested(obj, col) ?? "")
.toString()
.replace(/,/g, ",")
.replace(/\n/g, " ");
return sanitiseCell((getNested(obj, col) ?? "").toString());
})
.join(",");
})
.join("\n");
if (!options.titleRow) {
return content;
}
const firstRow = options.titleRow.map((s) => s.replace(/,/g, ",")).join(",");
const firstRow = options.titleRow.map(sanitiseCell).join(",");
return `${firstRow}\n${content}`;
},
};

0 comments on commit 0ee1887

Please sign in to comment.