♻️ Make user required in subscription model (#1585)

This commit is contained in:
Luke Vella 2025-02-27 15:23:01 +00:00 committed by GitHub
parent 01758f81ae
commit aebea5a41c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 87 additions and 92 deletions

View file

@ -24,26 +24,60 @@ export async function onCustomerSubscriptionCreated(event: Stripe.Event) {
throw new Error("Missing user ID");
}
// Create and update user
await prisma.user.update({
where: {
id: res.data.userId,
},
data: {
subscription: {
create: {
id: subscription.id,
active: isActive,
priceId,
currency,
interval,
amount,
status: subscription.status,
createdAt: toDate(subscription.created),
periodStart: toDate(subscription.current_period_start),
periodEnd: toDate(subscription.current_period_end),
const userId = res.data.userId;
// Check if user already has a subscription
const existingUser = await prisma.user.findUnique({
where: { id: userId },
include: { subscription: true },
});
if (!existingUser) {
throw new Error(`User with ID ${userId} not found`);
}
// If user already has a subscription, update it or replace it
if (existingUser.subscription) {
// Update the existing subscription with new data
await prisma.subscription.update({
where: { id: existingUser.subscription.id },
data: {
id: subscription.id,
active: isActive,
priceId,
currency,
interval,
amount,
status: subscription.status,
createdAt: toDate(subscription.created),
periodStart: toDate(subscription.current_period_start),
periodEnd: toDate(subscription.current_period_end),
cancelAtPeriodEnd: subscription.cancel_at_period_end,
},
});
} else {
// Create a new subscription for the user
await prisma.user.update({
where: {
id: userId,
},
data: {
subscription: {
create: {
id: subscription.id,
active: isActive,
priceId,
currency,
interval,
amount,
status: subscription.status,
createdAt: toDate(subscription.created),
periodStart: toDate(subscription.current_period_start),
periodEnd: toDate(subscription.current_period_end),
cancelAtPeriodEnd: subscription.cancel_at_period_end,
},
},
},
},
});
});
}
}