Skip to content

Instantly share code, notes, and snippets.

@NickyMeuleman
Created October 5, 2022 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickyMeuleman/62c8a7960d4fc3d5c9ff974f4d3bd640 to your computer and use it in GitHub Desktop.
Save NickyMeuleman/62c8a7960d4fc3d5c9ff974f4d3bd640 to your computer and use it in GitHub Desktop.
objects to CSV and CSV to objects
async function fromCSV({ ctx }) => {
const { filePaths } = await dialog.showOpenDialog({
filters: [{ name: "Comma seperated values", extensions: ["csv"] }],
});
const csv = fs.readFileSync(filePaths[0], { encoding: "utf-8" });
const lines = csv.split("\n");
const keys = lines.shift()?.split(",");
for (const line of lines) {
const obj: Record<string, string> = {};
const vals = line.split(",");
for (const i in keys) {
const idx = parseInt(i); // why JavaScript, why
const key = keys[idx];
const val = vals[idx];
obj[key] = val;
}
// transform and validate data with zod
// yeet it into prisma
}
});
async function toCSV({ctx}) {
const allRitten = await ctx.prisma.rit.findMany();
const header = Object.keys(allRitten[0]);
const rows = allRitten.map(
(rit) => Object.values(rit)
);
const csv = [header.join(","), ...rows.map((row) => row.join(","))].join(
"\n"
);
const { filePath } = await dialog.showSaveDialog({
title: "Choose path to save CSV",
filters: [{ name: "Comma seperated values", extensions: ["csv"] }],
});
if (filePath) {
fs.writeFileSync(filePath, csv, { encoding: "utf-8" });
}
}),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment