-
-
Notifications
You must be signed in to change notification settings - Fork 368
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
🔨 Add script for normalizing stripe subscription metadata
- Loading branch information
Showing
2 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
65 changes: 65 additions & 0 deletions
65
packages/billing/src/scripts/normalize-subscription-metadata.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
/** | ||
* This script will go through all subscriptions and add the userId to the metadata. | ||
*/ | ||
import { stripe } from "../lib/stripe"; | ||
import { prisma } from "@rallly/database"; | ||
|
||
async function getSubscriptionsWithMissingMetadata( | ||
starting_after?: string, | ||
): Promise<string[]> { | ||
const res: string[] = []; | ||
|
||
const subscriptions = await stripe.subscriptions.list({ | ||
limit: 100, | ||
starting_after, | ||
}); | ||
subscriptions.data.forEach((subscription) => { | ||
if (!subscription.metadata.userId) { | ||
res.push(subscription.id); | ||
} | ||
}); | ||
if (subscriptions.has_more) { | ||
return [ | ||
...res, | ||
...(await getSubscriptionsWithMissingMetadata( | ||
subscriptions.data[subscriptions.data.length - 1].id, | ||
)), | ||
]; | ||
} else { | ||
return res; | ||
} | ||
} | ||
|
||
async function normalizeSubscriptionMetadata() { | ||
const subscriptions = await getSubscriptionsWithMissingMetadata(); | ||
|
||
console.log( | ||
`Found ${subscriptions.length} subscriptions with missing metadata`, | ||
); | ||
|
||
for (const subscriptionId of subscriptions) { | ||
const user = await prisma.user.findFirst({ | ||
select: { | ||
id: true, | ||
}, | ||
where: { | ||
subscriptionId: subscriptionId, | ||
}, | ||
}); | ||
|
||
if (!user) { | ||
console.log("User not found for subscription", subscriptionId); | ||
continue; | ||
} | ||
|
||
await stripe.subscriptions.update(subscriptionId, { | ||
metadata: { | ||
userId: user.id, | ||
}, | ||
}); | ||
|
||
console.log("Updated subscription", subscriptionId); | ||
} | ||
} | ||
|
||
normalizeSubscriptionMetadata(); |