UNPKG

tsbase

Version:

Base class libraries for TypeScript

79 lines 3.24 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Csv = void 0; const Query_1 = require("../Patterns/CommandQuery/Query"); const Regex_1 = require("./Regex"); const Strings_1 = require("./Strings"); class Csv { constructor() { } /** * Accepts a json object and returns the CSV string equivalent. * @param json */ static EncodeAsCsv(headers, json) { const csvConversionResult = new Query_1.Query(() => { return this.convertToCSV(json); }).Execute(); return csvConversionResult.IsSuccess && csvConversionResult.Value ? `${headers.toString()}\r\n${csvConversionResult.Value}` : Strings_1.Strings.Empty; } /** * Accepts a csv string amd returns the JSON equivalent object. * @param csv * @param headerKeys sequential array of keys for each header in the given csv * @returns */ static DecodeAsJson(csv, headerKeys) { const json = []; const lines = csv.split('\n'); const headersString = lines.shift(); const headers = headersString && Regex_1.Regex.AggregateMatches(Regex_1.Regex.CsvData, headersString, [], (match, cv) => { match && cv.push(match[1]); }); if (!headers || !headerKeys.length || headers.length !== headerKeys.length) { console.error('Unable to decode CSV to JSON - ensure the given headerKeys is the same length as the CSV headers', `CSV Headers Count: ${headers === null || headers === void 0 ? void 0 : headers.length} | headerKeys Length: ${headerKeys.length}`); return json; } const valueString = lines.join('\n'); const recordValues = Regex_1.Regex.AggregateMatches(Regex_1.Regex.CsvData, valueString, [], (match, cv) => { if (cv.length === 0 || cv[cv.length - 1].length % headers.length === 0) { cv.push([]); } match && cv[cv.length - 1].push(match[1] || ''); }); recordValues.forEach(rv => { const entry = {}; headerKeys.forEach((k, i) => { if (k) { entry[k] = rv[i]; } }); json.push(entry); }); return json; } // eslint-disable-next-line complexity static convertToCSV(json) { const items = typeof json !== 'object' ? JSON.parse(json) : json; let str = Strings_1.Strings.Empty; for (let i = 0; i < items.length; i++) { const item = items[i]; let line = Strings_1.Strings.Empty; for (const key in item) { if (line !== Strings_1.Strings.Empty) { line += ','; } const value = item[key]; const literalQuotes = (value === null || value === void 0 ? void 0 : value.toString().includes(',')) ? '"' : ''; line += value !== Strings_1.Strings.Empty ? `${literalQuotes}"${value}"${literalQuotes}` : Strings_1.Strings.Empty; } str += line + '\r\n'; } return str.trim(); } } exports.Csv = Csv; //# sourceMappingURL=Csv.js.map