|
1 | 1 | import type Stripe from 'stripe'
|
| 2 | +import { cache } from '@stacksjs/cache' |
2 | 3 | import { stripe } from '..'
|
| 4 | +import { price } from '../drivers/stripe' |
3 | 5 |
|
4 | 6 | export interface PriceManager {
|
5 |
| - retrieveByLookupKey: (lookupKey: string) => Promise<Stripe.Price> |
| 7 | + retrieveByLookupKey: (lookupKey: string) => Promise<Stripe.Price | undefined> |
6 | 8 | createOrGet: (lookupKey: string, params: Stripe.PriceCreateParams) => Promise<Stripe.Price>
|
7 | 9 | }
|
8 | 10 |
|
9 | 11 | 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 | + } |
14 | 40 | }
|
15 | 41 |
|
16 | 42 | async function createOrGet(
|
|
0 commit comments