Skip to content

Instantly share code, notes, and snippets.

@jgatjens
Created February 9, 2023 05:37
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 jgatjens/6d48b478efc4eee4477621858593e6bd to your computer and use it in GitHub Desktop.
Save jgatjens/6d48b478efc4eee4477621858593e6bd to your computer and use it in GitHub Desktop.
Seed table from csv file with Prisma.
import { clinics, PrismaClient } from "@prisma/client";
import * as fs from "fs";
import * as path from "path";
import * as csv from "fast-csv";
const prisma = new PrismaClient();
type ClinicsCsvRow = Omit<clinics, "date_created" | "date_updated">;
async function main() {
fs.createReadStream(path.resolve(__dirname, "data-clinics_fixed.csv"))
.pipe(csv.parse({ headers: true }))
// pipe the parsed input into a csv formatter
.pipe(csv.format<ClinicsCsvRow, ClinicsCsvRow>({ headers: true }))
// Using the transform function from the formatting stream
.transform(async (row, next) => {
// If clinic data exist update it, otherwise create it
const res = await prisma.clinics.upsert({
where: { crm_id: row.crm_id },
update: {
...row,
},
create: {
...row,
},
});
return next(null, res);
})
.pipe(process.stdout)
.on("end", () => {
process.exit();
});
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment