import type { InteractionUpdate } from './feed.js'; import type { createInteractions, InteractionPost } from './interactions.js'; export type InteractionController = ReturnType; export function createInteractionController( service: ReturnType, reconcile: (update: InteractionUpdate) => void ) { let closed = false; async function write(operation: () => Promise, update: (result: T) => InteractionUpdate) { if (closed) throw new Error('Interactions are closed'); const result = await operation(); if (!closed) reconcile(update(result)); return result; } function postUpdate( post: InteractionPost, changes: Extract['changes'] ): InteractionUpdate { return { kind: 'post', uri: post.uri, cid: post.cid, changes }; } return { like(post: InteractionPost) { return write( () => service.like(post), (likeUri) => postUpdate(post, { likeUri }) ); }, unlike(post: InteractionPost, likeUri: string) { return write( () => service.unlike(post.uri, likeUri), () => postUpdate(post, { likeUri: null }) ); }, repost(post: InteractionPost) { return write( () => service.repost(post), (repostUri) => postUpdate(post, { repostUri }) ); }, unrepost(post: InteractionPost, repostUri: string) { return write( () => service.unrepost(post.uri, repostUri), () => postUpdate(post, { repostUri: null }) ); }, bookmark(post: InteractionPost) { return write( () => service.bookmark(post), () => postUpdate(post, { bookmarked: true }) ); }, unbookmark(post: InteractionPost) { return write( () => service.unbookmark(post.uri), () => postUpdate(post, { bookmarked: false }) ); }, follow(did: string) { return write( () => service.follow(did), (following) => ({ kind: 'actor', did, following }) ); }, unfollow(did: string, followUri: string) { return write( () => service.unfollow(did, followUri), () => ({ kind: 'actor', did, following: null }) ); }, mute(did: string) { return write( () => service.mute(did), () => ({ kind: 'actor', did, muted: true }) ); }, unmute(did: string) { return write( () => service.unmute(did), () => ({ kind: 'actor', did, muted: false }) ); }, block(did: string) { return write( () => service.block(did), (blocking) => ({ kind: 'actor', did, blocking }) ); }, unblock(did: string, blockUri: string) { return write( () => service.unblock(did, blockUri), () => ({ kind: 'actor', did, blocking: null }) ); }, close() { if (closed) return; closed = true; service.close(); } }; }