From 09da289859854e47808dd51caa0383006ce04a26 Mon Sep 17 00:00:00 2001 From: USpiri Date: Tue, 22 Oct 2024 13:24:26 -0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Feat:=20Improve=20csv=20and=20json?= =?UTF-8?q?=20file=20creation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/download-csv.ts | 80 ++++++++++++++------------------------- 1 file changed, 28 insertions(+), 52 deletions(-) diff --git a/src/utils/download-csv.ts b/src/utils/download-csv.ts index 492cf2d..e2b54e2 100644 --- a/src/utils/download-csv.ts +++ b/src/utils/download-csv.ts @@ -2,52 +2,24 @@ import { MapItem } from "../models/item.interface"; export const downloadMapItemsCSV = (data: MapItem[], fileName: string) => () => { - const csvValues = [ - [ - "Name", - "Rating", - "ReviewCount", - "Phone", - "Time", - "Category", - "Accesibility", - "Address", - "Features", - "Image", - "WebSite", - "GoogleMap", - ], - ...data.map((i) => [ - i.name, - i.rating, - i.reviewsCount, - i.phone, - i.time, - i.category, - i.isAccessible, - i.address, - i.features.join(" - "), - i.image, - i.website, - i.mapLink, - ]), - ] - .map((row) => row.join(",")) - .join("\n"); - data.forEach((i) => { - console.log(i); - }); + const header = Object.keys(data[0]); + const csv = [ + header.join(","), + // eslint-disable-next-line + ...data.map((row: any) => + header.map((fieldName) => { + const field = row[fieldName as keyof MapItem]; + return JSON.stringify( + Array.isArray(field) ? field.join(" - ") : field, + (_, value) => value ?? "", + ).replace(/\\"/g, '""'); + }), + ), + ].join("\n"); - const blob = new Blob([csvValues], { type: "text/csv" }); + const blob = new Blob([csv], { type: "text/csv" }); - const url = URL.createObjectURL(blob); - const link = document.createElement("a"); - link.href = url; - link.download = fileName; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - URL.revokeObjectURL(url); + downloadFile(blob, fileName); }; export const downloadMapItemsJSON = @@ -55,12 +27,16 @@ export const downloadMapItemsJSON = const json = JSON.stringify(data, null, 2); const blob = new Blob([json], { type: "application/json" }); - const url = URL.createObjectURL(blob); - const link = document.createElement("a"); - link.href = url; - link.download = fileName; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - URL.revokeObjectURL(url); + downloadFile(blob, fileName); }; + +const downloadFile = (file: Blob, fileName: string) => { + const url = URL.createObjectURL(file); + const link = document.createElement("a"); + link.href = url; + link.download = fileName; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); +};