Created
October 5, 2022 21:52
-
-
Save NickyMeuleman/62c8a7960d4fc3d5c9ff974f4d3bd640 to your computer and use it in GitHub Desktop.
objects to CSV and CSV to objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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