|
@@ -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));
|
|
|
+ }
|
|
|
}
|
|
|
}
|
|
|
}
|