Browse Source

init db via sdk

david 5 months ago
parent
commit
6802ea1bd6
2 changed files with 48 additions and 20 deletions
  1. 4 6
      README.md
  2. 44 14
      frontend/src/index.ts

+ 4 - 6
README.md

@@ -10,13 +10,13 @@ With SurrealDB installed Let's start out with a on-disk test database with a sin
 surreal start --user root --pass root rocksdb:/home/david/typescript_surrealdb_test/ts_test.db
 ```
 
-Now in our TypeScript project let's install the surrealdb sdk.
+In our TypeScript project let's install the surrealdb sdk.
 ```bash
 npm i surrealdb
 ```
 
-In the Surrealist GUI we create a schemaless table user with two fields: first_name and last_name. And we create two entries for that table 
-each with a randomly generated id. 
+Using the TypeScript sdk we create a schemaless table 'user' with two fields: first_name and last_name. 
+Also we create two test entries for that table. We then try to fetch and display these entries in our frontend.
 
 Running our vite development server
 ```bash
@@ -27,6 +27,4 @@ npm run dev
 Loading our page in the browser returns the stringified entries from our User table.
 
 [ { "first_name": "test2", "id": "User:svtic3xqkr5r50ea3sad", "last_name": "user" }, { "first_name": "test", "id": "User:znrhq8hubryi8tivxm3s", 
-"last_name": "user" } ]
-
-Now this was quite painless. Nice.
+"last_name": "user" } ]

+ 44 - 14
frontend/src/index.ts

@@ -1,17 +1,42 @@
-import Surreal from 'surrealdb';
+import Surreal, { RecordId } from 'surrealdb';
 
 const appContainer = document.getElementById('app');
 const db = new Surreal();
 
+type User = {  
+  id: string;
+  first_name: string;
+  last_name: string;
+}
+
+const auth = {
+    username: 'root',
+    password: 'root',
+}
+
+const db_url = "http://localhost:8000";
+const db_name = { namespace: "ts_test", database: "ts_test" };
+
+
+export async function initDb() {
+  try {
+    await db.connect(db_url, {auth});
+    await db.use(db_name);
+    //create test db with two test entries
+    //the first execution also creates the table if it does not exist yet
+    //ids must be defined otherwise a random id gets assigned and new user records are created on each page load
+    await db.create<User>("user", {id: "test1", first_name: "test1", last_name: "user"});
+    await db.create<User>("user", {id: "test2", first_name: "test2", last_name: "user"});
+  } catch (err) {
+    console.error("Failed to init db. Maybe it existed already.", err instanceof Error ? err.message : String(err));        
+    throw(err);
+  }
+}
+
 export async function getDb(): Promise<Surreal> {
   try {
-    await db.connect("http://localhost:8000", {
-      auth: {
-        username: 'root',
-        password: 'root',
-      }
-    });
-    await db.use({ namespace: "ts_test", database: "ts_test" });
+    await db.connect(db_url, {auth});
+    await db.use(db_name);
     return db;
   } catch (err) {
     console.error("Failed to connect to SurrealDB:", err instanceof Error ? err.message : String(err));
@@ -21,13 +46,18 @@ export async function getDb(): Promise<Surreal> {
 }
 
 async function run() {
-  if (appContainer) {
+  if (appContainer) {    
     try {
-      const db_con = await getDb();
-      const users = await db_con.select('User');      
-      appContainer.textContent = JSON.stringify(users, null, 2);
-    } catch (err) {
-      console.error("Failed to retrieve db_con:", err instanceof Error ? err.message : String(err));
+      await initDb();    
+    } catch {
+    } finally {
+      try {
+        const db_con = await getDb();
+        const users = await db_con.select('user');      
+        appContainer.textContent = JSON.stringify(users, null, 2);
+      } catch (err) {
+        console.error("Failed to retrieve db_con:", err instanceof Error ? err.message : String(err));
+      }
     }
   }
 }