Skip to content

Commit

Permalink
revalidate invoices per customer in events
Browse files Browse the repository at this point in the history
  • Loading branch information
collinschaafsma committed Oct 28, 2024
1 parent ddff5c0 commit 3df965c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ export const supportedStripeEvents = new Set([
"checkout.session.completed",
"customer.subscription.deleted",
"customer.subscription.updated",
"invoice.created",
"invoice.finalized",
"invoice.paid",
"payment_method.attached",
"product.created",
"product.deleted",
Expand Down
17 changes: 17 additions & 0 deletions services/event.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import "server-only"
import { revalidateTag } from "next/cache"
import { eq } from "drizzle-orm"
import Stripe from "stripe"
import { db } from "@/drizzle/db"
import { customers } from "@/drizzle/schema"
import { checkout } from "./checkout"
import { paymentMethod } from "./paymentMethod"
import { price } from "./price"
Expand Down Expand Up @@ -45,6 +49,19 @@ export const event = {
.object as Stripe.PaymentMethod
await paymentMethod.attach({ paymentMethodId: eventPaymentMethod.id })
break
case "invoice.finalized":
case "invoice.paid":
case "invoice.created":
const eventInvoice = constructedEvent.data.object as Stripe.Invoice
const customerId = eventInvoice.customer as string
const customer = await db.query.customers.findFirst({
where: eq(customers.stripeCustomerId, customerId),
})

if (customer?.userId) {
revalidateTag(`invoices:${customer.userId}`)
}
break
case "product.created":
case "product.updated":
const eventProduct = constructedEvent.data.object as Stripe.Product
Expand Down

0 comments on commit 3df965c

Please sign in to comment.