eletrotupi / tcc/ api/src/services/export/csv.serializer.tsed34b0497a309385687884b59eaa3b57c205df3d
1.1 KB | 37 lines Raw
1
import { stringify } from "csv-stringify/sync";
2

3
import { CsvTable, CsvValue, ExportFile } from "@app/services/export/types";
4

5
// Dates become ISO-8601 strings so they are quoted like any other string and
6
// sort unambiguously regardless of the reader's locale.
7
const normalize = (value: CsvValue): string | number | null => {
8
  if (value === null || value === undefined) return null;
9
  if (value instanceof Date) return value.toISOString();
10

11
  return value;
12
};
13

14
export function serializeCsv<Row>(table: CsvTable<Row>, rows: Row[]): ExportFile {
15
  const records = rows.map((row) => {
16
    const record: Record<string, string | number | null> = {};
17

18
    for (const column of table.columns) {
19
      record[column.header] = normalize(column.value(row));
20
    }
21

22
    return record;
23
  });
24

25
  const body = stringify(records, {
26
    header: true,
27
    columns: table.columns.map((column) => column.header),
28
    record_delimiter: "\r\n",
29
    quoted_string: true,
30
  });
31

32
  return {
33
    filename: table.filename,
34
    content: Buffer.from(`\ufeff${body}`, "utf8"),
35
    rows: rows.length,
36
  };
37
}