feat: migrate from PocketBase to PostgreSQL with Drizzle ORM

- Add @project-e/db package with Drizzle schema and migrations
- Replace PocketBase client with PostgreSQL-based database client
- Migrate auth from custom to NextAuth.js
- Add Docker Compose with PostgreSQL container
- Update worker to use new database client
- Remove PocketBase-specific files and migrations
- Add drizzle config and initial migration
This commit is contained in:
2026-07-24 07:08:29 -04:00
parent 6c438eab32
commit 73335484f8
42 changed files with 2895 additions and 2796 deletions
@@ -0,0 +1,6 @@
import NextAuth from 'next-auth';
import { authOptions } from '@/lib/auth-config';
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
-52
View File
@@ -1,52 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { createPocketBaseClient } from '@/lib/pocketbase';
import { z } from 'zod';
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(1),
});
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { email, password } = loginSchema.parse(body);
const pb = createPocketBaseClient();
// Authenticate with PocketBase
const authData = await pb.collection('users').authWithPassword(email, password);
// Set auth token in httpOnly cookie
const response = NextResponse.json({
user: {
id: authData.record.id,
email: authData.record.email,
name: authData.record.name || authData.record.email,
},
token: authData.token,
});
response.cookies.set('pb_auth', authData.token, {
httpOnly: true,
secure: process.env.COOKIE_SECURE === 'true',
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 7, // 7 days
});
return response;
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: error.issues } },
{ status: 400 }
);
}
return NextResponse.json(
{ error: { code: 'AUTH_ERROR', message: 'Invalid email or password' } },
{ status: 401 }
);
}
}
-16
View File
@@ -1,16 +0,0 @@
import { NextResponse } from 'next/server';
export async function POST() {
const response = NextResponse.json({ success: true });
// Clear auth cookie
response.cookies.set('pb_auth', '', {
httpOnly: true,
secure: process.env.COOKIE_SECURE === 'true',
sameSite: 'lax',
path: '/',
maxAge: 0, // Expire immediately
});
return response;
}
+4 -16
View File
@@ -1,29 +1,17 @@
import { NextRequest, NextResponse } from 'next/server';
import { createPocketBaseClient } from '@/lib/pocketbase';
import { getAuthUser } from '@/lib/auth';
export async function GET(request: NextRequest) {
try {
const token = request.cookies.get('pb_auth')?.value;
if (!token) {
const user = await getAuthUser(request);
if (!user) {
return NextResponse.json(
{ error: { code: 'UNAUTHORIZED', message: 'Not authenticated' } },
{ status: 401 }
);
}
const pb = createPocketBaseClient(token);
// Get current user
const authData = await pb.collection('users').authRefresh();
return NextResponse.json({
user: {
id: authData.record.id,
email: authData.record.email,
name: authData.record.name || authData.record.email,
},
});
return NextResponse.json({ user });
} catch {
return NextResponse.json(
{ error: { code: 'AUTH_ERROR', message: 'Invalid or expired token' } },
-41
View File
@@ -1,41 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { createPocketBaseClient } from '@/lib/pocketbase';
export async function POST(request: NextRequest) {
try {
const token = request.cookies.get('pb_auth')?.value;
if (!token) {
return NextResponse.json(
{ error: { code: 'UNAUTHORIZED', message: 'No auth token' } },
{ status: 401 }
);
}
const pb = createPocketBaseClient(token);
// Refresh the auth token
await pb.collection('users').authRefresh();
const newToken = pb.authStore.token;
const response = NextResponse.json({
token: newToken,
});
response.cookies.set('pb_auth', newToken, {
httpOnly: true,
secure: process.env.COOKIE_SECURE === 'true',
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 7, // 7 days
});
return response;
} catch {
return NextResponse.json(
{ error: { code: 'AUTH_ERROR', message: 'Token refresh failed' } },
{ status: 401 }
);
}
}
+19 -40
View File
@@ -1,6 +1,6 @@
import { NextRequest } from 'next/server';
import { getAuthUser, getAuthToken } from '@/lib/auth';
import { createPocketBaseClient } from '@/lib/pocketbase';
import { getAuthUser } from '@/lib/auth';
import postgres from 'postgres';
export const dynamic = 'force-dynamic';
export const maxDuration = 300; // 5 minutes
@@ -15,7 +15,7 @@ const DEFAULT_COLLECTIONS = [
'notifications',
];
// GET /api/realtime — Multiplexed SSE endpoint for PocketBase realtime subscriptions
// GET /api/realtime — Multiplexed SSE endpoint backed by PostgreSQL LISTEN/NOTIFY.
export async function GET(request: NextRequest) {
const user = await getAuthUser(request);
if (!user) {
@@ -36,10 +36,10 @@ export async function GET(request: NextRequest) {
const subscribedCollections =
collections.length > 0 ? collections : DEFAULT_COLLECTIONS;
const token = getAuthToken(request);
const pb = createPocketBaseClient(token || undefined);
const encoder = new TextEncoder();
const unsubscribeFns: Array<() => Promise<void>> = [];
const listener = postgres(process.env.DATABASE_URL!, { max: 1 });
let unlisten: (() => Promise<void>) | undefined;
let keepalive: ReturnType<typeof setInterval> | undefined;
const stream = new ReadableStream({
async start(controller) {
@@ -50,53 +50,32 @@ export async function GET(request: NextRequest) {
)
);
// Subscribe to each collection
for (const collection of subscribedCollections) {
const subscription = await listener.listen('project_e_events', (payload) => {
try {
const unsub = await pb.collection(collection).subscribe('*', (e) => {
try {
const event = {
type: e.action,
collection,
record: e.record,
};
controller.enqueue(
encoder.encode(`data: ${JSON.stringify(event)}\n\n`)
);
} catch {
// Controller might be closed
}
});
unsubscribeFns.push(unsub);
const event = JSON.parse(payload) as { collection?: string };
if (!event.collection || subscribedCollections.includes(event.collection)) {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
}
} catch {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ type: 'subscription_error', collection })}\n\n`
)
);
// Ignore malformed database notifications and closed streams.
}
}
});
unlisten = subscription.unlisten;
// Keepalive ping every 30 seconds
const keepalive = setInterval(() => {
keepalive = setInterval(() => {
try {
controller.enqueue(encoder.encode(':ping\n\n'));
} catch {
clearInterval(keepalive);
if (keepalive) clearInterval(keepalive);
}
}, 30000);
},
async cancel() {
// Client disconnected — cleanup all subscriptions
for (const unsub of unsubscribeFns) {
try {
await unsub();
} catch {
// Ignore cleanup errors
}
}
unsubscribeFns.length = 0;
if (keepalive) clearInterval(keepalive);
await unlisten?.();
await listener.end({ timeout: 5 });
},
});