Skip to content

Commit 4ea2536

Browse files
committed
Postgres Self-hosting Dashboard Demo
1 parent 3061162 commit 4ea2536

70 files changed

Lines changed: 3279 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# next.js
12+
/.next/
13+
/out/
14+
15+
# production
16+
/build
17+
18+
# misc
19+
.DS_Store
20+
*.pem
21+
22+
# debug
23+
npm-debug.log*
24+
yarn-debug.log*
25+
yarn-error.log*
26+
27+
# local env files
28+
.env*.local
29+
30+
# vercel
31+
.vercel
32+
33+
# typescript
34+
*.tsbuildinfo
35+
next-env.d.ts
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { NextRequest, NextResponse } from 'next/server';
2+
import { deleteComment } from '../store';
3+
4+
export async function POST(request: NextRequest) {
5+
try {
6+
const body = await request.json();
7+
const { commentAnnotationId } = body;
8+
9+
console.log('[Velt API] DELETE comment:', commentAnnotationId);
10+
11+
if (commentAnnotationId) {
12+
await deleteComment(commentAnnotationId);
13+
}
14+
15+
return NextResponse.json({ success: true });
16+
} catch (error) {
17+
console.error('[Velt API] Error deleting comment:', error);
18+
return NextResponse.json({ success: false, error: 'Failed to delete' }, { status: 500 });
19+
}
20+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { NextRequest, NextResponse } from 'next/server';
2+
import { getComments } from '../store';
3+
4+
export async function POST(request: NextRequest) {
5+
try {
6+
const body = await request.json();
7+
const { organizationId, commentAnnotationIds, documentIds } = body;
8+
9+
console.log('[Velt API] GET comments:', { organizationId, commentAnnotationIds, documentIds });
10+
11+
const result = await getComments({
12+
organizationId,
13+
commentAnnotationIds,
14+
documentIds,
15+
});
16+
17+
return NextResponse.json({ result, success: true });
18+
} catch (error) {
19+
console.error('[Velt API] Error getting comments:', error);
20+
return NextResponse.json({ result: {}, success: true }, { status: 200 });
21+
}
22+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { NextRequest, NextResponse } from 'next/server';
2+
import { saveComments } from '../store';
3+
4+
export async function POST(request: NextRequest) {
5+
try {
6+
const body = await request.json();
7+
const { commentAnnotation, metadata } = body;
8+
9+
console.log('[Velt API] SAVE comments:', { commentAnnotation, metadata });
10+
11+
if (commentAnnotation) {
12+
// Extract documentId and organizationId from metadata
13+
const documentId = metadata?.documentId;
14+
const organizationId = metadata?.organizationId;
15+
await saveComments(commentAnnotation, { documentId, organizationId });
16+
}
17+
18+
return NextResponse.json({ success: true });
19+
} catch (error) {
20+
console.error('[Velt API] Error saving comments:', error);
21+
return NextResponse.json({ success: false, error: 'Failed to save' }, { status: 500 });
22+
}
23+
}
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
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+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { NextRequest, NextResponse } from 'next/server';
2+
3+
// [Velt] API key and auth token from environment variables
4+
const NEXT_PUBLIC_VELT_API_KEY = "6xTcUFtlYAlCdh11zrKB";
5+
const VELT_AUTH_TOKEN = "bd4d5226050470b6c658054fcdf1092a";
6+
7+
export async function POST(req: NextRequest) {
8+
try {
9+
const { userId, organizationId, email, isAdmin } = await req.json();
10+
if (!userId || !organizationId) {
11+
return NextResponse.json({ error: 'Missing userId or organizationId' }, { status: 400 });
12+
}
13+
if (!VELT_AUTH_TOKEN) {
14+
return NextResponse.json({ error: 'Server configuration error: missing VELT_AUTH_TOKEN' }, { status: 500 });
15+
}
16+
const body = {
17+
data: {
18+
userId,
19+
userProperties: {
20+
organizationId,
21+
...(typeof isAdmin === 'boolean' ? { isAdmin } : {}),
22+
...(email ? { email } : {}),
23+
},
24+
},
25+
};
26+
const res = await fetch('https://api.velt.dev/v2/auth/token/get', {
27+
method: 'POST',
28+
headers: { 'Content-Type': 'application/json', 'x-velt-api-key': NEXT_PUBLIC_VELT_API_KEY, 'x-velt-auth-token': VELT_AUTH_TOKEN },
29+
body: JSON.stringify(body),
30+
});
31+
const json = await res.json();
32+
const token = json?.result?.data?.token;
33+
if (!res.ok || !token) {
34+
return NextResponse.json({ error: json?.error?.message || 'Failed to generate token' }, { status: 500 });
35+
}
36+
return NextResponse.json({ token });
37+
} catch {
38+
return NextResponse.json({ error: 'Internal error' }, { status: 500 });
39+
}
40+
}

0 commit comments

Comments
 (0)