Skip to content

Commit

Permalink
feat: added export as csv service
Browse files Browse the repository at this point in the history
  • Loading branch information
akshatmittal61 committed Sep 22, 2023
1 parent 8bc0c39 commit 4ffb170
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
11 changes: 7 additions & 4 deletions pages/admin/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { EventCard } from "@/components/admin";
import useDevice from "@/hooks/device";
import styles from "@/styles/pages/admin/Dashboard.module.scss";
import { fetchGlobalStats } from "@/utils/api/stats";
import { exportAsJSON } from "@/services/files";
import { exportAsCSV } from "@/services/files";

const classes = stylesConfig(styles, "admin-dashboard");

Expand Down Expand Up @@ -278,10 +278,13 @@ const AdminDashboard: React.FC = () => {
<Button
variant="outline"
onClick={() => {
exportAsJSON(
exportAsCSV(
globalStats.map((stat) => ({
name: stat.event.name,
teamSize: stat.event.teamSize,
teamSize:
stat.event.teamSize === 1
? "Solo Event"
: stat.event.teamSize,
participants: stat.participants,
teams: stat.teams,
})),
Expand All @@ -290,7 +293,7 @@ const AdminDashboard: React.FC = () => {
}}
size="medium"
>
Download as JSON
Download as CSV
</Button>
</div>
{gettingStats ? (
Expand Down
17 changes: 17 additions & 0 deletions services/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,20 @@ export const exportAsJSON = (data: any, name: string) => {
const json = JSON.stringify(data, null, 2);
saveFile(json, name, "json");
};

export const jsonToCsv = (json: any[]) => {
const replacer = (_: any, value: any) => (value === null ? "" : value);
const header = Object.keys(json[0]);
let csv = json.map((row: any) =>
header
.map((fieldName) => JSON.stringify(row[fieldName], replacer))
.join(",")
);
csv.unshift(header.join(","));
return csv.join("\r\n");
};

export const exportAsCSV = (data: any[], name: string) => {
const csv = jsonToCsv(data);
saveFile(csv, name, "csv");
};

0 comments on commit 4ffb170

Please sign in to comment.