UNPKG

@geogirafe/lib-geoportal

Version:

GeoGirafe is a flexible application to build online geoportals.

74 lines (73 loc) 2.87 kB
import { download } from './download'; import GirafeSingleton from '../../base/GirafeSingleton'; import ConfigManager from '../configuration/configmanager'; import I18nManager from '../i18n/i18nmanager'; export default class CsvManager extends GirafeSingleton { constructor(type) { super(type); Object.defineProperty(this, "configManager", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "i18nManager", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.i18nManager = I18nManager.getInstance(); this.configManager = ConfigManager.getInstance(); } get config() { return this.configManager.Config; } /** * Generate a CSV. * @param data Entries/objects to include in the CSV. * @param columnDefs Column definitions. * @returns The CSV file as string. */ generateCsv(data, columnDefs) { if (data.length == 0 || columnDefs.length == 0) { return ''; } const translatedColumnHeaders = columnDefs.map((columnHeader) => this.i18nManager.getTranslation(columnHeader.name)); const header = this.getRow(translatedColumnHeaders); const dataRows = data.map((values) => { const rowValues = columnDefs.map((columnHeader) => values[columnHeader.name]); return this.getRow(rowValues); }); return this.config.csv.includeHeader ? header + dataRows.join('') : dataRows.join(''); } /** * @param values Values. * @returns CSV row. */ getRow(values) { const matchAllQuotesRegex = new RegExp(this.config.csv.quote, 'g'); const doubleQuote = this.config.csv.quote + this.config.csv.quote; const rowValues = values.map((value) => { if (value !== undefined && value !== null) { const strValue = `${value}`; // wrap each value into quotes and escape quotes with double quotes return `${this.config.csv.quote}${strValue.replace(matchAllQuotesRegex, doubleQuote)}${this.config.csv.quote}`; } else { return ''; } }); return `${rowValues.join(this.config.csv.separator)}\n`; } /** * Generate a CSV and start a download with the generated file. * @param data Entries/objects to include in the CSV. * @param columnDefs Column definitions. * @param fileName The CSV file name, without the extension. */ startDownload(data, columnDefs, fileName) { const fileContent = this.generateCsv(data, columnDefs); download(fileContent, fileName, `text/csv;charset=${this.config.csv.encoding}`); } }