import Surreal from 'surrealdb'; /** * Connects to the SurrealDB instance and authenticates with the user's JWT. * This enforces row-level security defined in the schema. * * @param token - The user's app-specific (SurrealDB) JWT * @returns The authenticated SurrealDB instance */ export async function connectToDB(token: string): Promise { const SURREALDB_URL = process.env.SURREALDB_URL; const SURREALDB_NAMESPACE = process.env.SURREALDB_NS; const SURREALDB_DATABASE = process.env.SURREALDB_DB; if (!SURREALDB_URL || !SURREALDB_NAMESPACE || !SURREALDB_DATABASE) { throw new Error('SurrealDB configuration is missing'); } // Create a new instance for each request to avoid connection state issues const db = new Surreal(); // Connect to SurrealDB await db.connect(SURREALDB_URL); // Authenticate as the user for this request. // This enforces the row-level security (PERMISSIONS) // defined in the schema for all subsequent queries. await db.authenticate(token); // Use the correct namespace and database await db.use({ namespace: SURREALDB_NAMESPACE, database: SURREALDB_DATABASE, }); return db; }