Skip to content

Commit

Permalink
✨ Feat: Improve csv and json file creation
Browse files Browse the repository at this point in the history
  • Loading branch information
USpiri committed Oct 22, 2024
1 parent f0660e2 commit 09da289
Showing 1 changed file with 28 additions and 52 deletions.
80 changes: 28 additions & 52 deletions src/utils/download-csv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,65 +2,41 @@ 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 =
(data: MapItem[], fileName: string) => () => {
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);
};

0 comments on commit 09da289

Please sign in to comment.