|
| 1 | +// PostgreSQL store for Velt comments |
| 2 | +// Docs: https://docs.velt.dev/self-host-data/comments |
| 3 | + |
| 4 | +import { Pool } from 'pg'; |
| 5 | + |
| 6 | +export type CommentAnnotation = { |
| 7 | + annotationId: string; |
| 8 | + documentId?: string; |
| 9 | + organizationId?: string; |
| 10 | + metadata?: unknown; |
| 11 | + comments: Record<string, { commentId: string | number; commentHtml?: string; commentText?: string }>; |
| 12 | +}; |
| 13 | + |
| 14 | +// PostgreSQL connection string |
| 15 | +const DATABASE_URL = process.env.DATABASE_URL; |
| 16 | + |
| 17 | +if (!DATABASE_URL && process.env.NODE_ENV === 'production') { |
| 18 | + console.warn('[PostgreSQL] WARNING: DATABASE_URL not set. Database operations will fail.'); |
| 19 | +} |
| 20 | + |
| 21 | +const TABLE_NAME = 'comment_annotations'; |
| 22 | + |
| 23 | +// Create a connection pool for serverless environments |
| 24 | +let pool: Pool | null = null; |
| 25 | +let initPromise: Promise<void> | null = null; |
| 26 | + |
| 27 | +function getPool(): Pool { |
| 28 | + if (!pool) { |
| 29 | + pool = new Pool({ |
| 30 | + connectionString: DATABASE_URL, |
| 31 | + ssl: DATABASE_URL?.includes('sslmode=require') ? { rejectUnauthorized: false } : false, |
| 32 | + max: 10, |
| 33 | + idleTimeoutMillis: 30000, |
| 34 | + connectionTimeoutMillis: 10000, |
| 35 | + }); |
| 36 | + } |
| 37 | + return pool; |
| 38 | +} |
| 39 | + |
| 40 | +async function ensureInitialized(): Promise<void> { |
| 41 | + if (!initPromise) { |
| 42 | + initPromise = initializeTable(); |
| 43 | + } |
| 44 | + return initPromise; |
| 45 | +} |
| 46 | + |
| 47 | +async function initializeTable(): Promise<void> { |
| 48 | + const client = await getPool().connect(); |
| 49 | + try { |
| 50 | + await client.query(` |
| 51 | + CREATE TABLE IF NOT EXISTS ${TABLE_NAME} ( |
| 52 | + annotation_id TEXT PRIMARY KEY, |
| 53 | + document_id TEXT, |
| 54 | + organization_id TEXT, |
| 55 | + data JSONB NOT NULL, |
| 56 | + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), |
| 57 | + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() |
| 58 | + ) |
| 59 | + `); |
| 60 | + |
| 61 | + // Create indexes for faster queries |
| 62 | + await client.query(` |
| 63 | + CREATE INDEX IF NOT EXISTS idx_${TABLE_NAME}_document_id ON ${TABLE_NAME}(document_id) |
| 64 | + `); |
| 65 | + await client.query(` |
| 66 | + CREATE INDEX IF NOT EXISTS idx_${TABLE_NAME}_organization_id ON ${TABLE_NAME}(organization_id) |
| 67 | + `); |
| 68 | + |
| 69 | + console.log('[PostgreSQL] Table initialized:', TABLE_NAME); |
| 70 | + } finally { |
| 71 | + client.release(); |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +export async function getComments(filters: { |
| 76 | + organizationId?: string; |
| 77 | + commentAnnotationIds?: string[]; |
| 78 | + documentIds?: string[]; |
| 79 | +}): Promise<Record<string, CommentAnnotation>> { |
| 80 | + await ensureInitialized(); |
| 81 | + const client = await getPool().connect(); |
| 82 | + try { |
| 83 | + const conditions: string[] = []; |
| 84 | + const values: unknown[] = []; |
| 85 | + let paramIndex = 1; |
| 86 | + |
| 87 | + if (filters.commentAnnotationIds?.length) { |
| 88 | + conditions.push(`annotation_id = ANY($${paramIndex})`); |
| 89 | + values.push(filters.commentAnnotationIds); |
| 90 | + paramIndex++; |
| 91 | + } |
| 92 | + if (filters.documentIds?.length) { |
| 93 | + conditions.push(`document_id = ANY($${paramIndex})`); |
| 94 | + values.push(filters.documentIds); |
| 95 | + paramIndex++; |
| 96 | + } |
| 97 | + if (filters.organizationId) { |
| 98 | + conditions.push(`organization_id = $${paramIndex}`); |
| 99 | + values.push(filters.organizationId); |
| 100 | + paramIndex++; |
| 101 | + } |
| 102 | + |
| 103 | + const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''; |
| 104 | + const query = `SELECT annotation_id, data FROM ${TABLE_NAME} ${whereClause}`; |
| 105 | + |
| 106 | + const result = await client.query(query, values); |
| 107 | + |
| 108 | + // Convert to Record format expected by Velt |
| 109 | + const annotations: Record<string, CommentAnnotation> = {}; |
| 110 | + for (const row of result.rows) { |
| 111 | + const annotation = row.data as CommentAnnotation; |
| 112 | + annotations[row.annotation_id] = annotation; |
| 113 | + } |
| 114 | + |
| 115 | + return annotations; |
| 116 | + } finally { |
| 117 | + client.release(); |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +export async function saveComments( |
| 122 | + annotations: Record<string, CommentAnnotation>, |
| 123 | + context?: { documentId?: string; organizationId?: string } |
| 124 | +): Promise<void> { |
| 125 | + if (Object.keys(annotations).length === 0) return; |
| 126 | + |
| 127 | + await ensureInitialized(); |
| 128 | + const client = await getPool().connect(); |
| 129 | + try { |
| 130 | + // Use a transaction for batch upserts |
| 131 | + await client.query('BEGIN'); |
| 132 | + |
| 133 | + for (const [id, annotation] of Object.entries(annotations)) { |
| 134 | + const documentId = context?.documentId || annotation.documentId || null; |
| 135 | + const organizationId = context?.organizationId || annotation.organizationId || null; |
| 136 | + |
| 137 | + // Store the full annotation with annotationId included |
| 138 | + const data = { |
| 139 | + ...annotation, |
| 140 | + annotationId: id, |
| 141 | + documentId, |
| 142 | + organizationId, |
| 143 | + }; |
| 144 | + |
| 145 | + await client.query( |
| 146 | + `INSERT INTO ${TABLE_NAME} (annotation_id, document_id, organization_id, data, updated_at) |
| 147 | + VALUES ($1, $2, $3, $4, NOW()) |
| 148 | + ON CONFLICT (annotation_id) |
| 149 | + DO UPDATE SET |
| 150 | + document_id = EXCLUDED.document_id, |
| 151 | + organization_id = EXCLUDED.organization_id, |
| 152 | + data = EXCLUDED.data, |
| 153 | + updated_at = NOW()`, |
| 154 | + [id, documentId, organizationId, JSON.stringify(data)] |
| 155 | + ); |
| 156 | + } |
| 157 | + |
| 158 | + await client.query('COMMIT'); |
| 159 | + } catch (error) { |
| 160 | + await client.query('ROLLBACK'); |
| 161 | + throw error; |
| 162 | + } finally { |
| 163 | + client.release(); |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +export async function deleteComment(annotationId: string): Promise<boolean> { |
| 168 | + await ensureInitialized(); |
| 169 | + const client = await getPool().connect(); |
| 170 | + try { |
| 171 | + const result = await client.query( |
| 172 | + `DELETE FROM ${TABLE_NAME} WHERE annotation_id = $1`, |
| 173 | + [annotationId] |
| 174 | + ); |
| 175 | + return (result.rowCount ?? 0) > 0; |
| 176 | + } finally { |
| 177 | + client.release(); |
| 178 | + } |
| 179 | +} |
0 commit comments