fleet/frontend/utilities/convert_to_csv/index.ts
jacobshandling ec11e3d1d0
fleetctl, API, copy updates around host identifiers (#20220)
## Addresses #19127 
![Screenshot 2024-07-08 at 4 49
33 PM](https://github.com/fleetdm/fleet/assets/61553566/b4704eb9-9707-4cbf-8959-ec67dde57103)
- Also replace all ocurrences of "comma separated" with
"comma-separated"

- [x] Changes file added for user-visible changes in `changes/`
- [x] `SELECT *` is avoided, SQL injection is prevented (using
placeholders for values in statements)
- [x] Added/updated tests
- [x] Manual QA for all new/changed functionality

---------

Co-authored-by: Jacob Shandling <jacob@fleetdm.com>
2024-07-09 10:25:01 -07:00

47 lines
1.4 KiB
TypeScript

const defaultFieldSortFunc = (fields: string[]) => fields;
interface ConvertToCSV {
objArray: any[]; // TODO: typing
fieldSortFunc?: (fields: string[]) => string[];
tableHeaders?: any[]; // TODO: typing
}
const formatFieldForCSV = (value: any): string => {
// If the value is an object, stringify it first
if (typeof value === "object") {
value = JSON.stringify(value);
}
// Escape double quotes in the value by doubling them
if (typeof value === "string") {
value = value.replace(/"/g, '""');
}
// Wrap the value in double quotes to enclose any value that may
// have a, or a " in it to distinguish them from a comma-separated delimiter
return `"${value}"`;
};
const convertToCSV = ({
objArray,
fieldSortFunc = defaultFieldSortFunc,
tableHeaders,
}: ConvertToCSV) => {
const tableHeadersStrings: string[] = tableHeaders
? tableHeaders.map((header: { id: string }) => header.id)
: Object.keys(objArray[0]);
let fields = fieldSortFunc(tableHeadersStrings);
// TODO: Revisit after v5 if column names are modified/removed from API response.
fields = fields.filter((field) => field !== "Host");
// Revisit end
const headerRow = fields.map((field) => formatFieldForCSV(field)).join(",");
const dataRows = objArray.map((row) =>
fields.map((field) => formatFieldForCSV(row[field])).join(",")
);
return [headerRow, ...dataRows].join("\n");
};
export default convertToCSV;