From 3df965cfb58922e9211b25df05e7e96f617febdc Mon Sep 17 00:00:00 2001 From: Collin Schaafsma Date: Sun, 27 Oct 2024 20:04:26 -0600 Subject: [PATCH] revalidate invoices per customer in events --- lib/constants.ts | 3 +++ services/event.ts | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/lib/constants.ts b/lib/constants.ts index aec1c0b..c73d433 100644 --- a/lib/constants.ts +++ b/lib/constants.ts @@ -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", diff --git a/services/event.ts b/services/event.ts index 609035e..01bfe55 100644 --- a/services/event.ts +++ b/services/event.ts @@ -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" @@ -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