Skip to content

Instantly share code, notes, and snippets.

@dillionverma
Last active December 11, 2023 19:41
Show Gist options
  • Save dillionverma/f3251d047ec983c40b85a915a0546673 to your computer and use it in GitHub Desktop.
Save dillionverma/f3251d047ec983c40b85a915a0546673 to your computer and use it in GitHub Desktop.
Seed Prisma DB from Stripe
model User {
id String @id @unique @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
name String?
email String? @unique
emailVerified DateTime?
image String?
role Role @default(USER)
customer Customer? // User can be a customer
accounts Account[]
sessions Session[]
@@index([id])
}
// Stripe Customer
model Customer {
id String @id @default(uuid())
user User? @relation(fields: [userId], references: [id])
userId String? @unique
stripeId String @unique
Payment Payment[]
@@index([userId])
}
// Stripe Payment
model Payment {
id String @id @default(uuid())
stripeId String @unique
amount Int
currency String
customer Customer @relation(fields: [customerId], references: [id])
customerId String
@@index([customerId])
}
import { PrismaClient } from "@prisma/client";
import Stripe from "stripe";
const db = new PrismaClient();
export const stripe = new Stripe(process.env.STRIPE_API_KEY!, {
apiVersion: "2022-11-15",
typescript: true,
});
class StripeService {
async getCustomers() {
const customers = [];
for await (const customer of stripe.customers.list()) {
customers.push(customer);
}
return customers;
}
async getPaymentIntents(customerId: string) {
const payments = [];
for await (const payment of stripe.charges.list({ customer: customerId })) {
payments.push(payment);
}
return payments;
}
}
async function seed() {
const stripe = new StripeService();
const customers = await stripe.getCustomers();
for (const c of customers) {
if (!c.email) throw new Error("Customer email is required");
try {
const user = await db.user.upsert({
where: { email: c.email },
update: {},
create: { email: c.email },
});
const customer = await db.customer.upsert({
where: { stripeId: c.id },
update: {},
create: {
stripeId: c.id,
user: { connect: { id: user.id } },
},
});
const stripePayments = await stripe.getPaymentIntents(c.id);
for (const stripePayment of stripePayments) {
await db.payment.create({
data: {
stripeId: stripePayment.id,
amount: stripePayment.amount,
currency: stripePayment.currency,
customerId: customer.id,
},
});
}
console.log("✅ " + c.email);
} catch (e) {
console.log("❌ " + c.email);
}
}
}
seed()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await db.$disconnect();
});
@dillionverma
Copy link
Author

dillionverma commented Jun 30, 2023

How to run:

npx tsx prisma/seed.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment