import Subscription from 'stripe' ; import { query } from '../utils/PostgresConnection' ; import { pg as sql } from 'yesql' ; import { getConfig } from '../utils/config' ; import { stripe } from '../utils/StripeClientManager' ; import { constructUpsertSql } from '../utils/helpers' ; import { subscriptionSchema } from '../schemas/subscription' ; import { verifyCustomerExists , fetchAndInsertCustomer } from './customers' ; const config = getConfig ( ) ; export const upsertSubscription = async ( subscription ) : Promise < Subscription . Subscription [ ] > => { const customerId = subscription ?. customer ?. toString ( ) ; if ( customerId && ! ( await verifyCustomerExists ( customerId ) ) ) { await fetchAndInsertCustomer ( customerId ) ; } const upsertString = constructUpsertSql ( config . SCHEMA || 'stripe' , 'subscriptions' , subscriptionSchema ) ; const prepared = sql ( upsertString ) ( subscription ) ; const { rows } = await query ( prepared . text , prepared . values ) ; return rows ; } ; export const verifySubscriptionExists = async ( id ) : Promise < boolean > => { const prepared = sql ( `
    select id from "${ config . SCHEMA }"."subscriptions" 
    where id = :id;
    ` ) ( { id } ) ; const { rows } = await query ( prepared . text , prepared . values ) ; return rows . length > 0 ; } ; export const fetchAndInsertSubscription = async ( id ) : Promise < Subscription . Subscription [ ] > => { const subscription = await stripe . subscriptions . retrieve ( id ) ; return upsertSubscription ( subscription ) ; } ;