Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type safety for retrieving customerId from event #13

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,12 +206,10 @@ This is the function called in the endpoint that actually takes the Stripe event
```ts
async function processEvent(event: Stripe.Event) {
// Skip processing if the event isn't one I'm tracking (list of all events below)
if (!allowedEvents.includes(event.type)) return;
if (!isAllowedStripeEvent(event)) return;

// All the events I track have a customerId
const { customer: customerId } = event?.data?.object as {
customer: string; // Sadly TypeScript does not know this
};
const { customer: customerId } = event.data.object;

// This helps make it typesafe and also lets me know if my assumption is wrong
if (typeof customerId !== "string") {
Expand All @@ -229,7 +227,7 @@ async function processEvent(event: Stripe.Event) {
If there are more I should be tracking for updates, please file a PR. If they don't affect subscription state, I do not care.

```ts
const allowedEvents: Stripe.Event.Type[] = [
export const allowedEvents = [
"checkout.session.completed",
"customer.subscription.created",
"customer.subscription.updated",
Expand All @@ -248,7 +246,13 @@ const allowedEvents: Stripe.Event.Type[] = [
"payment_intent.succeeded",
"payment_intent.payment_failed",
"payment_intent.canceled",
];
] as const satisfies readonly Stripe.Event.Type[];

export type AllowedEventType = typeof allowedEvents[number];
export type AllowedStripeEvent = Extract<Stripe.Event, { type: AllowedEventType }>;

export const isAllowedStripeEvent = (event: Stripe.Event): event is AllowedStripeEvent =>
allowedEvents.includes(event.type as AllowedEventType)
```

### Custom Stripe subscription type
Expand Down