a tool for shared writing and social publishing
1"use server"; 2 3import { drizzle } from "drizzle-orm/node-postgres"; 4import { email_subscriptions_to_entity, facts } from "drizzle/schema"; 5import postgres from "postgres"; 6import { eq, and, sql } from "drizzle-orm"; 7import type { Fact } from "src/replicache"; 8import { v7 } from "uuid"; 9import { pool } from "supabase/pool"; 10 11export async function deleteSubscription(subscriptionID: string) { 12 const client = await pool.connect(); 13 const db = drizzle(client); 14 15 try { 16 await db.transaction(async (db) => { 17 let [subscription] = await db 18 .select() 19 .from(email_subscriptions_to_entity) 20 .where(eq(email_subscriptions_to_entity.id, subscriptionID)); 21 if (!subscription) return; 22 let [fact] = (await db 23 .select() 24 .from(facts) 25 .where( 26 and( 27 eq(facts.entity, subscription.entity), 28 29 eq(facts.attribute, "mailbox/subscriber-count"), 30 ), 31 )) as Fact<"mailbox/subscriber-count">[]; 32 if (fact) { 33 await db 34 .update(facts) 35 .set({ 36 data: sql`${{ type: "number", value: fact.data.value - 1 }}::jsonb`, 37 }) 38 .where(eq(facts.id, fact.id)); 39 } 40 await db 41 .delete(email_subscriptions_to_entity) 42 .where(eq(email_subscriptions_to_entity.id, subscriptionID)); 43 }); 44 45 client.release(); 46 return { success: true }; 47 } catch (error) { 48 console.error("Error unsubscribing:", error); 49 client.release(); 50 return { success: false, error: "Failed to unsubscribe" }; 51 } 52}