Skip to content

Commit a13b6c6

Browse files
chore: wip
1 parent 8462037 commit a13b6c6

File tree

1 file changed

+31
-5
lines changed
  • storage/framework/core/payments/src/billable

1 file changed

+31
-5
lines changed

storage/framework/core/payments/src/billable/price.ts

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,42 @@
11
import type Stripe from 'stripe'
2+
import { cache } from '@stacksjs/cache'
23
import { stripe } from '..'
4+
import { price } from '../drivers/stripe'
35

46
export interface PriceManager {
5-
retrieveByLookupKey: (lookupKey: string) => Promise<Stripe.Price>
7+
retrieveByLookupKey: (lookupKey: string) => Promise<Stripe.Price | undefined>
68
createOrGet: (lookupKey: string, params: Stripe.PriceCreateParams) => Promise<Stripe.Price>
79
}
810

911
export const managePrice: PriceManager = (() => {
10-
async function retrieveByLookupKey(lookupKey: string): Promise<Stripe.Price> {
11-
const prices = await stripe.price.list({ lookup_keys: [lookupKey] })
12-
13-
return prices.data[0]
12+
async function retrieveByLookupKey(lookupKey: string): Promise<Stripe.Price | undefined> {
13+
const cachedPrice = cache.get(`price_${lookupKey}`)
14+
15+
if (cachedPrice) {
16+
try {
17+
// If cached value is a string, parse it; otherwise, it's already a parsed object
18+
return typeof cachedPrice === 'string' ? JSON.parse(cachedPrice) : cachedPrice
19+
}
20+
catch (error) {
21+
console.error('Error parsing cached price:', error)
22+
}
23+
}
24+
25+
try {
26+
const prices = await stripe.price.list({ lookup_keys: [lookupKey] })
27+
28+
if (!prices.data.length)
29+
return undefined
30+
31+
const price = prices.data[0]
32+
cache.set(`price_${lookupKey}`, JSON.stringify(price))
33+
34+
return price
35+
}
36+
catch (error) {
37+
console.error('Error retrieving price from Stripe:', error)
38+
return undefined
39+
}
1440
}
1541

1642
async function createOrGet(

0 commit comments

Comments
 (0)