Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Use kysely for sqlite

Hakan Shehu56cd41a6708f
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
index 2fda0289..ecf738c8 100644
--- a/desktop/package-lock.json
+++ b/desktop/package-lock.json
@@ -25,6 +25,7 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"electron-squirrel-startup": "^1.0.1",
+ "kysely": "^0.27.4",
"mobx": "^6.13.1",
"mobx-react-lite": "^4.0.7",
"re-resizable": "^6.9.17",
@@ -7776,6 +7777,15 @@
"json-buffer": "3.0.1"
}
},
+ "node_modules/kysely": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/kysely/-/kysely-0.27.4.tgz",
+ "integrity": "sha512-dyNKv2KRvYOQPLCAOCjjQuCk4YFd33BvGdf/o5bC7FiW+BB6snA81Zt+2wT9QDFzKqxKa5rrOmvlK/anehCcgA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
"node_modules/levn": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
diff --git a/desktop/package.json b/desktop/package.json
index 37a0abfc..cd5485c7 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -59,6 +59,7 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"electron-squirrel-startup": "^1.0.1",
+ "kysely": "^0.27.4",
"mobx": "^6.13.1",
"mobx-react-lite": "^4.0.7",
"re-resizable": "^6.9.17",
diff --git a/desktop/src/components/app.tsx b/desktop/src/components/app.tsx
index 815f0a5c..411166b0 100644
--- a/desktop/src/components/app.tsx
+++ b/desktop/src/components/app.tsx
@@ -15,17 +15,16 @@ export const App = observer(() => {
React.useEffect(() => {
if (!store.loaded) {
- Promise.all([
- window.globalDb.getAccounts(),
- window.globalDb.getWorkspaces(),
- ]).then(([accounts, workspaces]) => {
- store.setAccounts(accounts);
- store.setWorkspaces(workspaces);
- store.setLoaded();
- }).catch((error) => {
- // Handle any errors if needed
- console.error("Error loading data: ", error);
- });
+ window.globalDb.init()
+ .then(({accounts, workspaces}) => {
+ store.setAccounts(accounts);
+ store.setWorkspaces(workspaces);
+ store.setLoaded();
+ })
+ .catch((error) => {
+ // Handle any errors if needed
+ console.error("Error loading data: ", error);
+ });
}
}, [store.loaded]);
diff --git a/desktop/src/components/spaces/space-create-dialog.tsx b/desktop/src/components/spaces/space-create-dialog.tsx
index 0b47a252..37debb94 100644
--- a/desktop/src/components/spaces/space-create-dialog.tsx
+++ b/desktop/src/components/spaces/space-create-dialog.tsx
@@ -119,7 +119,7 @@ export const SpaceCreateDialog = ({
<Button variant="outline" onClick={handleCancel}>
Cancel
</Button>
- <Button type="submit">
+ <Button type="submit" disabled={isPending}>
{isPending && <Spinner className="mr-1" />}
Create
</Button>
diff --git a/desktop/src/components/workspaces/sidebar-header.tsx b/desktop/src/components/workspaces/sidebar-header.tsx
index 678c75f0..c8ce8e92 100644
--- a/desktop/src/components/workspaces/sidebar-header.tsx
+++ b/desktop/src/components/workspaces/sidebar-header.tsx
@@ -38,11 +38,11 @@ export const SidebarHeader = observer(() => {
</div>
<hr className="-mx-1 my-1 h-px bg-muted"/>
<h2 className="text-sm font-semibold">Workspaces</h2>
- <ul className="flex flex-col gap-2">
+ <ul className="flex flex-col gap-0.5">
{workspaces.map((w) => {
return (
<li key={w.id}
- className="flex flex-row p-2 pl-0 items-center gap-2 hover:cursor-pointer hover:bg-gray-100 rounded-md">
+ className="flex flex-row p-2 pl-1 items-center gap-2 hover:cursor-pointer hover:bg-gray-100 rounded-md">
<Avatar id={w.id} name={w.name} className="h-7 w-7"/>
<p>{w.name}</p>
</li>
@@ -69,6 +69,5 @@ export const SidebarHeader = observer(() => {
</div>
</PopoverContent>
</Popover>
-
)
});
\ No newline at end of file
diff --git a/desktop/src/components/workspaces/workspace.tsx b/desktop/src/components/workspaces/workspace.tsx
index deabc874..8d58b614 100644
--- a/desktop/src/components/workspaces/workspace.tsx
+++ b/desktop/src/components/workspaces/workspace.tsx
@@ -15,7 +15,21 @@ export const Workspace = observer(() => {
const workspace = workspaces[0];
return (
- <WorkspaceContext.Provider value={workspace}>
+ <WorkspaceContext.Provider value={{
+ ...workspace,
+ addNode: async (node) => {
+ await window.workspaceDb.addNode(workspace.accountId, workspace.id, node);
+ },
+ getNodes: async () => {
+ return await window.workspaceDb.getNodes(workspace.accountId, workspace.id);
+ },
+ updateNode: async (node) => {
+ await window.workspaceDb.updateNode(workspace.accountId, workspace.id, node);
+ },
+ deleteNode: async (nodeId) => {
+ await window.workspaceDb.deleteNode(workspace.accountId, workspace.id, nodeId);
+ },
+ }}>
<div className="flex h-screen max-h-screen flex-row">
<div className="w-96">
<Sidebar />
diff --git a/desktop/src/contexts/workspace.ts b/desktop/src/contexts/workspace.ts
index 057ad79b..032428ad 100644
--- a/desktop/src/contexts/workspace.ts
+++ b/desktop/src/contexts/workspace.ts
@@ -1,8 +1,16 @@
import { createContext, useContext } from 'react';
import { Workspace } from "@/types/workspaces";
+import {Node} from "@/types/nodes";
-export const WorkspaceContext = createContext<Workspace>(
- {} as Workspace,
+interface WorkspaceContext extends Workspace {
+ addNode: (node: Node) => Promise<void>
+ getNodes: () => Promise<Node[]>
+ updateNode: (node: Node) => Promise<void>
+ deleteNode: (nodeId: string) => Promise<void>
+}
+
+export const WorkspaceContext = createContext<WorkspaceContext>(
+ {} as WorkspaceContext,
);
export const useWorkspace = () => useContext(WorkspaceContext);
diff --git a/desktop/src/electron/database/global/index.ts b/desktop/src/electron/database/global/index.ts
new file mode 100644
index 00000000..fd8937c0
--- /dev/null
+++ b/desktop/src/electron/database/global/index.ts
@@ -0,0 +1,180 @@
+import {app} from "electron";
+import SQLite from "better-sqlite3";
+import {Kysely, Migration, Migrator, SqliteDialect} from "kysely";
+import { GlobalDatabaseSchema } from "@/electron/database/global/schema";
+import {Account} from "@/types/accounts";
+import {Workspace} from "@/types/workspaces";
+import {AccountTransactions, Transaction} from "@/types/transactions";
+import {globalDatabaseMigrations} from "@/electron/database/global/migrations";
+import {GlobalDatabaseData} from "@/types/global";
+
+class GlobalDatabase {
+ database: Kysely<GlobalDatabaseSchema>;
+
+ constructor() {
+ const appPath = app.getPath('userData');
+ const dialect = new SqliteDialect({
+ database: new SQLite(`${appPath}/global.db`),
+ });
+
+ this.database = new Kysely<GlobalDatabaseSchema>({
+ dialect
+ });
+ }
+
+ init = async (): Promise<GlobalDatabaseData> => {
+ await this.migrate();
+
+ const accounts = await this.getAccounts();
+ const workspaces = await this.getWorkspaces();
+
+ return {
+ accounts,
+ workspaces
+ };
+ }
+
+ migrate = async () => {
+ const migrator = new Migrator({
+ db: this.database,
+ provider: {
+ getMigrations(): Promise<Record<string, Migration>> {
+ return Promise.resolve(globalDatabaseMigrations);
+ }
+ }
+ })
+
+ await migrator.migrateToLatest();
+ }
+
+ getAccounts = async (): Promise<Account[]> => {
+ const accounts = await this.database
+ .selectFrom('accounts')
+ .selectAll()
+ .execute();
+
+ return accounts.map((account) => ({
+ id: account.id,
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
+ token: account.token
+ }));
+ }
+
+ addAccount = async (account: Account) => {
+ await this.database
+ .insertInto('accounts')
+ .values(account)
+ .execute();
+ }
+
+ getWorkspaces = async (): Promise<Workspace[]> => {
+ const workspaces = await this.database
+ .selectFrom('workspaces')
+ .selectAll()
+ .execute();
+
+ return workspaces.map(workspace => ({
+ id: workspace.id,
+ name: workspace.name,
+ description: workspace.description,
+ avatar: workspace.avatar,
+ versionId: workspace.version_id,
+ accountId: workspace.account_id,
+ role: workspace.role,
+ userNodeId: workspace.user_node_id
+ }));
+ }
+
+ addWorkspace = async (workspace: Workspace) => {
+ await this.database
+ .insertInto('workspaces')
+ .values({
+ id: workspace.id,
+ name: workspace.name,
+ description: workspace.description,
+ avatar: workspace.avatar,
+ version_id: workspace.versionId,
+ account_id: workspace.accountId,
+ role: workspace.role,
+ user_node_id: workspace.userNodeId
+ })
+ .execute();
+ }
+
+ addTransaction = async (transaction: Transaction) => {
+ console.log(transaction);
+ await this.database
+ .insertInto('transactions')
+ .values({
+ id: transaction.id,
+ type: transaction.type,
+ account_id: transaction.accountId,
+ input: transaction.input,
+ node_id: transaction.nodeId,
+ created_at: transaction.createdAt.toISOString(),
+ workspace_id: transaction.workspaceId
+ })
+ .execute();
+ }
+
+ getGroupedAccountTransactions = async (count: number): Promise<AccountTransactions[]> => {
+ const transactions = await this.database
+ .selectFrom('transactions')
+ .selectAll()
+ .limit(count)
+ .execute();
+
+ if (transactions.length === 0) {
+ return [];
+ }
+
+ const accountIds = transactions.map(transaction => transaction.account_id);
+ const accounts = await this.database
+ .selectFrom('accounts')
+ .selectAll()
+ .where('id', 'in', accountIds)
+ .execute();
+
+ const transactionsMap = new Map<string, Transaction[]>();
+ transactions.forEach(transaction => {
+ const input = JSON.parse(transaction.input);
+ const transactionObj = {
+ id: transaction.id,
+ workspaceId: transaction.workspace_id,
+ accountId: transaction.account_id,
+ type: transaction.type,
+ nodeId: transaction.node_id,
+ input: input,
+ createdAt: new Date(transaction.created_at)
+ };
+
+ if (transactionsMap.has(transaction.account_id)) {
+ transactionsMap.get(transaction.account_id)?.push(transactionObj);
+ } else {
+ transactionsMap.set(transaction.account_id, [transactionObj]);
+ }
+ });
+
+ return accounts.map(account => ({
+ account: {
+ id: account.id,
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
+ token: account.token
+ },
+ transactions: transactionsMap.get(account.id) || []
+ }));
+ }
+
+ deleteTransactions = async (ids: string[]) => {
+ await this.database
+ .deleteFrom('transactions')
+ .where('id', 'in', ids)
+ .execute();
+ }
+}
+
+export const globalDatabase = new GlobalDatabase();
\ No newline at end of file
diff --git a/desktop/src/electron/database/global/migrations.ts b/desktop/src/electron/database/global/migrations.ts
new file mode 100644
index 00000000..0a2f86b7
--- /dev/null
+++ b/desktop/src/electron/database/global/migrations.ts
@@ -0,0 +1,60 @@
+import {Migration} from "kysely";
+
+const createAccountsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('accounts')
+ .addColumn('id', 'text', (col) => col.notNull())
+ .addColumn('name', 'text', (col) => col.notNull())
+ .addColumn('email', 'text', (col) => col.notNull())
+ .addColumn('avatar', 'text')
+ .addColumn('token', 'text', (col) => col.notNull())
+ .execute()
+ },
+ down: async (db) => {
+ await db.schema.dropTable('accounts').execute()
+ }
+}
+
+const createWorkspacesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('workspaces')
+ .addColumn('id', 'text', (col) => col.notNull())
+ .addColumn('name', 'text', (col) => col.notNull())
+ .addColumn('description', 'text')
+ .addColumn('avatar', 'text')
+ .addColumn('version_id', 'text', (col) => col.notNull())
+ .addColumn('account_id', 'integer', (col) => col.notNull())
+ .addColumn('role', 'integer', (col) => col.notNull())
+ .addColumn('user_node_id', 'text', (col) => col.notNull())
+ .execute()
+ },
+ down: async (db) => {
+ await db.schema.dropTable('workspaces').execute()
+ }
+}
+
+const createTransactionsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('transactions')
+ .addColumn('id', 'text', (col) => col.notNull())
+ .addColumn('workspace_id', 'text', (col) => col.notNull())
+ .addColumn('account_id', 'text', (col) => col.notNull())
+ .addColumn('type', 'text', (col) => col.notNull())
+ .addColumn('node_id', 'text', (col) => col.notNull())
+ .addColumn('input', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .execute()
+ },
+ down: async (db) => {
+ await db.schema.dropTable('transactions').execute()
+ }
+}
+
+export const globalDatabaseMigrations: Record<string, Migration> = {
+ '202408011709_create_accounts_table': createAccountsTable,
+ '202408011712_create_workspaces_table': createWorkspacesTable,
+ '202408011715_create_transactions_table': createTransactionsTable
+}
\ No newline at end of file
diff --git a/desktop/src/electron/database/global/schema.ts b/desktop/src/electron/database/global/schema.ts
new file mode 100644
index 00000000..c50b9bf9
--- /dev/null
+++ b/desktop/src/electron/database/global/schema.ts
@@ -0,0 +1,34 @@
+export interface AccountsTableSchema {
+ id: string;
+ name: string;
+ email: string;
+ avatar: string | null;
+ token: string;
+}
+
+export interface WorkspacesTableSchema {
+ id: string;
+ name: string;
+ description: string | null;
+ avatar: string | null;
+ version_id: string;
+ account_id: string;
+ role: number;
+ user_node_id: string;
+}
+
+export interface TransactionsTableSchema {
+ id: string;
+ workspace_id: string;
+ account_id: string;
+ type: string;
+ node_id: string;
+ input: string;
+ created_at: string;
+}
+
+export interface GlobalDatabaseSchema {
+ accounts: AccountsTableSchema;
+ workspaces: WorkspacesTableSchema;
+ transactions: TransactionsTableSchema;
+}
\ No newline at end of file
diff --git a/desktop/src/electron/database/workspace/index.ts b/desktop/src/electron/database/workspace/index.ts
new file mode 100644
index 00000000..04c1f0af
--- /dev/null
+++ b/desktop/src/electron/database/workspace/index.ts
@@ -0,0 +1,52 @@
+import {app} from "electron";
+import SQLite from "better-sqlite3";
+import {Kysely, Migration, Migrator, SqliteDialect} from "kysely";
+import { GlobalDatabaseSchema } from "@/electron/database/global/schema";
+import {workspaceDatabaseMigrations} from "@/electron/database/workspace/migrations";
+import * as fs from "node:fs";
+
+class WorkspaceDatabase {
+ database: Kysely<GlobalDatabaseSchema>;
+
+ constructor(accountId: string, workspaceId: string) {
+ const appPath = app.getPath('userData');
+ const accountPath = `${appPath}/account_${accountId}`;
+ if (!fs.existsSync(accountPath)) {
+ fs.mkdirSync(accountPath);
+ }
+
+ const dialect = new SqliteDialect({
+ database: new SQLite(`${accountPath}/workspace_${workspaceId}.db`),
+ });
+
+ this.database = new Kysely<GlobalDatabaseSchema>({
+ dialect,
+ });
+ }
+
+ migrate = async () => {
+ const migrator = new Migrator({
+ db: this.database,
+ provider: {
+ getMigrations(): Promise<Record<string, Migration>> {
+ return Promise.resolve(workspaceDatabaseMigrations);
+ }
+ }
+ })
+
+ await migrator.migrateToLatest();
+ }
+}
+
+const workspaceDatabasesMap = new Map<string, WorkspaceDatabase>();
+
+export const getWorkspaceDatabase = async (accountId: string, workspaceId: string) => {
+ const key = `${accountId}/${workspaceId}`;
+ if (!workspaceDatabasesMap.has(key)) {
+ const workspaceDatabase = new WorkspaceDatabase(accountId, workspaceId);
+ await workspaceDatabase.migrate();
+ workspaceDatabasesMap.set(key, workspaceDatabase);
+ }
+
+ return workspaceDatabasesMap.get(key)!;
+}
\ No newline at end of file
diff --git a/desktop/src/electron/database/workspace/migrations.ts b/desktop/src/electron/database/workspace/migrations.ts
new file mode 100644
index 00000000..053d1e44
--- /dev/null
+++ b/desktop/src/electron/database/workspace/migrations.ts
@@ -0,0 +1,27 @@
+import {Migration} from "kysely";
+
+const createNodesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('nodes')
+ .addColumn('id', 'text', (col) => col.notNull())
+ .addColumn('workspace_id', 'text', (col) => col.notNull())
+ .addColumn('parent_id', 'text')
+ .addColumn('type', 'text', (col) => col.notNull())
+ .addColumn('attrs', 'text')
+ .addColumn('content', 'text')
+ .addColumn('created_at', 'timestamp', (col) => col.notNull())
+ .addColumn('updated_at', 'timestamp')
+ .addColumn('created_by', 'text', (col) => col.notNull())
+ .addColumn('updated_by', 'text')
+ .addColumn('version_id', 'text', (col) => col.notNull())
+ .execute()
+ },
+ down: async (db) => {
+ await db.schema.dropTable('nodes').execute()
+ }
+}
+
+export const workspaceDatabaseMigrations: Record<string, Migration> = {
+ '202408011756_create_nodes_table': createNodesTable
+}
\ No newline at end of file
diff --git a/desktop/src/electron/database/workspace/schema.ts b/desktop/src/electron/database/workspace/schema.ts
new file mode 100644
index 00000000..9273ff0a
--- /dev/null
+++ b/desktop/src/electron/database/workspace/schema.ts
@@ -0,0 +1,17 @@
+export interface NodesTableSchema {
+ id: string;
+ workspace_id: string;
+ parent_id: string | null;
+ type: string;
+ attrs: string | null;
+ content: string | null;
+ created_at: Date;
+ updated_at: Date | null;
+ created_by: string;
+ updated_by: string | null;
+ version_id: string;
+}
+
+export interface WorkspaceDatabaseSchema {
+ nodes: NodesTableSchema;
+}
\ No newline at end of file
diff --git a/desktop/src/electron/event-loop.ts b/desktop/src/electron/event-loop.ts
index 47f626ee..4fc52b46 100644
--- a/desktop/src/electron/event-loop.ts
+++ b/desktop/src/electron/event-loop.ts
@@ -1,13 +1,24 @@
-import {deleteTransactions, getGroupedAccountTransactions} from "@/electron/global-db";
+import {globalDatabase} from "@/electron/database/global";
+import {getWorkspaceDatabase} from "@/electron/database/workspace";
export const initEventLoop = () => {
setInterval(async () => {
+ await initWorkspaceDatabases();
await sendTransactions();
}, 10000);
}
+const initWorkspaceDatabases = async () => {
+ const workspaces = await globalDatabase.getWorkspaces();
+
+ for (const workspace of workspaces) {
+ const workspaceDatabase = await getWorkspaceDatabase(workspace.accountId, workspace.id);
+ await workspaceDatabase.migrate();
+ }
+}
+
const sendTransactions = async () => {
- const groupedAccountTransactions = getGroupedAccountTransactions(10);
+ const groupedAccountTransactions = await globalDatabase.getGroupedAccountTransactions(20);
for (const accountTransactions of groupedAccountTransactions) {
const transactionIds = accountTransactions.transactions.map(t => t.id);
@@ -23,7 +34,7 @@ const sendTransactions = async () => {
});
if (response.ok) {
- deleteTransactions(transactionIds);
+ await globalDatabase.deleteTransactions(transactionIds);
}
}
}
diff --git a/desktop/src/electron/global-db.ts b/desktop/src/electron/global-db.ts
deleted file mode 100644
index 7097c6d3..00000000
--- a/desktop/src/electron/global-db.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import {app, ipcMain} from "electron";
-import database from 'better-sqlite3';
-import {Workspace} from "@/types/workspaces";
-import {AccountTransactions, Transaction} from "@/types/transactions";
-import {Account} from "@/types/accounts";
-import {AccountDbModel, TransactionDbModel, WorkspaceDbModel} from "@/electron/models";
-
-const path = app.getPath('userData');
-const globalDb = new database(`${path}/global.db`);
-
-const createAccountsTableQuery = `
- CREATE TABLE IF NOT EXISTS accounts (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- email TEXT NOT NULL,
- avatar TEXT,
- token TEXT NOT NULL
- );
-`;
-
-const createWorkspacesTableQuery = `
- CREATE TABLE IF NOT EXISTS workspaces (
- id TEXT,
- name TEXT NOT NULL,
- description TEXT,
- avatar TEXT,
- version_id TEXT NOT NULL,
- account_id TEXT NOT NULL,
- role INTEGER NOT NULL,
- user_node_id TEXT NOT NULL
- );
-`;
-
-
-const createTransactionsTableQuery = `
- CREATE TABLE IF NOT EXISTS transactions (
- id TEXT PRIMARY KEY,
- workspace_id TEXT NOT NULL,
- account_id TEXT NOT NULL,
- type TEXT NOT NULL,
- node_id TEXT NOT NULL,
- input TEXT NOT NULL,
- created_at TEXT NOT NULL
- );
-`;
-
-const insertAccountQuery = `
- INSERT INTO accounts
- (
- id,
- name,
- email,
- avatar,
- token
- )
- VALUES (?, ?, ?, ?, ?)
-`;
-
-const selectAccountsQuery = `
- SELECT id, name, email, avatar, token FROM accounts
-`;
-
-const selectWorkspacesQuery = `
- SELECT
- id,
- name,
- description,
- avatar,
- version_id,
- account_id,
- role,
- user_node_id
- FROM workspaces
-`;
-
-const insertWorkspaceQuery = `
- INSERT INTO workspaces
- (
- id,
- name,
- description,
- avatar,
- version_id,
- account_id,
- role,
- user_node_id
- )
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
-`;
-
-const insertTransactionQuery = `
- INSERT INTO transactions
- (
- id,
- workspace_id,
- account_id,
- type,
- node_id,
- input,
- created_at
- )
- VALUES (?, ?, ?, ?, ?, ?, ?)
-`;
-
-const deleteTransactionsQuery = `
- DELETE FROM transactions WHERE id IN (?)
-`;
-
-
-const addAccount = (account: Account) => {
- const stmt = globalDb.prepare(insertAccountQuery);
- stmt.run(account.id, account.name, account.email, account.avatar, account.token);
-}
-
-const getAccounts = (): Account[] => {
- const stmt = globalDb.prepare<[], AccountDbModel>(selectAccountsQuery);
- const accounts = stmt.all();
-
- return accounts.map(account => ({
- id: account.id,
- name: account.name,
- email: account.email,
- avatar: account.avatar,
- token: account.token
- }));
-}
-
-const getWorkspaces = (): Workspace[] => {
- const stmt = globalDb.prepare<[], WorkspaceDbModel>(selectWorkspacesQuery);
- const workspaces = stmt.all();
-
- return workspaces.map(workspace => ({
- id: workspace.id,
- name: workspace.name,
- description: workspace.description,
- avatar: workspace.avatar,
- versionId: workspace.version_id,
- accountId: workspace.account_id,
- role: workspace.role,
- userNodeId: workspace.user_node_id
- }));
-}
-
-const addWorkspace = (workspace: Workspace) => {
- const stmt = globalDb.prepare(insertWorkspaceQuery);
- stmt.run(workspace.id, workspace.name, workspace.description, workspace.avatar, workspace.versionId, workspace.accountId, workspace.role, workspace.userNodeId);
-}
-
-const enqueueTransaction = (transaction: Transaction) => {
- const stmt = globalDb.prepare(insertTransactionQuery);
- const inputJson = JSON.stringify(transaction.input);
- stmt.run(transaction.id, transaction.workspaceId, transaction.accountId, transaction.type, transaction.nodeId, inputJson, transaction.createdAt.toISOString());
-}
-
-export const getGroupedAccountTransactions = (count: number): AccountTransactions[] => {
- const stmt = globalDb.prepare<[], TransactionDbModel>(`SELECT * FROM transactions ORDER BY id LIMIT ${count} `);
- const transactions = stmt.all();
-
- if (transactions.length === 0) {
- return [];
- }
-
- const accountIds = transactions.map(transaction => transaction.account_id);
- const placeholders = accountIds.map(() => '?').join(',');
- const accountStmt = globalDb.prepare<string[], AccountDbModel>(`SELECT * FROM accounts WHERE id IN (${placeholders})`);
- const accounts = accountStmt.all(...accountIds);
-
- const transactionsMap = new Map<string, Transaction[]>();
- transactions.forEach(transaction => {
- const input = JSON.parse(transaction.input);
- const transactionObj = {
- id: transaction.id,
- workspaceId: transaction.workspace_id,
- accountId: transaction.account_id,
- type: transaction.type,
- nodeId: transaction.node_id,
- input: input,
- createdAt: new Date(transaction.created_at)
- };
-
- if (transactionsMap.has(transaction.account_id)) {
- transactionsMap.get(transaction.account_id)?.push(transactionObj);
- } else {
- transactionsMap.set(transaction.account_id, [transactionObj]);
- }
- });
-
- return accounts.map(account => ({
- account: {
- id: account.id,
- name: account.name,
- email: account.email,
- avatar: account.avatar,
- token: account.token
- },
- transactions: transactionsMap.get(account.id) || []
- }));
-}
-
-export const deleteTransactions = (ids: string[]) => {
- const stmt = globalDb.prepare(deleteTransactionsQuery);
- stmt.run(ids.join(','));
-}
-
-export const initGlobalDb = () => {
- globalDb.exec(createWorkspacesTableQuery);
- globalDb.exec(createTransactionsTableQuery);
- globalDb.exec(createAccountsTableQuery);
-}
-
-export const defineGlobalDbHandlers = () => {
- ipcMain.handle('get-accounts', () => getAccounts());
- ipcMain.handle('add-account', (_, account: Account) => addAccount(account));
- ipcMain.handle('get-workspaces', () => getWorkspaces());
- ipcMain.handle('add-workspace', (_, workspace: Workspace) => addWorkspace(workspace));
- ipcMain.handle('enqueue-transaction', (event, transaction: Transaction) => enqueueTransaction(transaction));
-}
\ No newline at end of file
diff --git a/desktop/src/electron/models.ts b/desktop/src/electron/models.ts
deleted file mode 100644
index 62536734..00000000
--- a/desktop/src/electron/models.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-export type AccountDbModel = {
- id: string;
- name: string;
- email: string;
- avatar?: string;
- token: string;
-};
-
-export type WorkspaceDbModel = {
- id: string;
- name: string;
- description?: string;
- avatar?: string;
- version_id: string;
- account_id: string;
- role: number;
- user_node_id: string;
-}
-
-export type TransactionDbModel = {
- id: string;
- workspace_id: string;
- account_id: string;
- type: string;
- node_id: string;
- input: string;
- created_at: number;
-};
\ No newline at end of file
diff --git a/desktop/src/lib/nodes.ts b/desktop/src/lib/nodes.ts
index 5dd8d620..351feb02 100644
--- a/desktop/src/lib/nodes.ts
+++ b/desktop/src/lib/nodes.ts
@@ -24,5 +24,5 @@ export const createNode = async (accountId: string, node: Node) => {
workspaceId: node.workspaceId,
accountId: accountId
}
- await window.globalDb.enqueueTransaction(transaction);
+ await window.globalDb.addTransaction(transaction);
}
\ No newline at end of file
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index ea247049..10d6ba76 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -1,6 +1,6 @@
-import { app, BrowserWindow } from 'electron';
+import { app, ipcMain, BrowserWindow } from 'electron';
import path from 'path';
-import {defineGlobalDbHandlers, initGlobalDb} from "@/electron/global-db";
+import { globalDatabase } from "@/electron/database/global";
import {initEventLoop} from "@/electron/event-loop";
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
@@ -9,8 +9,6 @@ if (require('electron-squirrel-startup')) {
}
const createWindow = () => {
- initGlobalDb();
-
// Create the browser window.
const mainWindow = new BrowserWindow({
fullscreen: true,
@@ -28,8 +26,6 @@ const createWindow = () => {
// Open the DevTools.
mainWindow.webContents.openDevTools();
-
- defineGlobalDbHandlers();
};
// This method will be called when Electron has finished
@@ -54,7 +50,12 @@ app.on('activate', () => {
}
});
-// In this file you can include the rest of your app's specific main process
-// code. You can also put them in separate files and import them here.
+// inter process handlers
+ipcMain.handle('init', async () => globalDatabase.init());
+ipcMain.handle('get-accounts', async () => globalDatabase.getAccounts());
+ipcMain.handle('add-account', async (_, account) => globalDatabase.addAccount(account));
+ipcMain.handle('get-workspaces', async () => globalDatabase.getWorkspaces());
+ipcMain.handle('add-workspace', async (_, workspace) => globalDatabase.addWorkspace(workspace));
+ipcMain.handle('add-transaction', async (_, transaction) => globalDatabase.addTransaction(transaction));
initEventLoop();
\ No newline at end of file
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index 47501707..1d05f10b 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -2,11 +2,20 @@ import { contextBridge, ipcRenderer } from 'electron';
import {Account} from "@/types/accounts";
import {Workspace} from "@/types/workspaces";
import {Transaction} from "@/types/transactions";
+import {Node} from "@/types/nodes";
contextBridge.exposeInMainWorld('globalDb', {
+ init: () => ipcRenderer.invoke('init'),
getAccounts: () => ipcRenderer.invoke('get-accounts'),
addAccount: (account: Account) => ipcRenderer.invoke('add-account', account),
getWorkspaces: () => ipcRenderer.invoke('get-workspaces'),
addWorkspace: (workspace: Workspace) => ipcRenderer.invoke('add-workspace', workspace),
- enqueueTransaction: (transaction: Transaction) => ipcRenderer.invoke('enqueue-transaction', transaction),
+ addTransaction: (transaction: Transaction) => ipcRenderer.invoke('add-transaction', transaction),
});
+
+contextBridge.exposeInMainWorld('workspaceDb', {
+ addNode: (accountId: string, workspaceId: string, node: Node) => ipcRenderer.invoke('add-node', accountId, workspaceId, node),
+ getNodes: (accountId: string, workspaceId: string) => ipcRenderer.invoke('get-nodes', accountId, workspaceId),
+ updateNode: (accountId: string, workspaceId: string, node: Node) => ipcRenderer.invoke('update-node', accountId, workspaceId, node),
+ deleteNode: (accountId: string, workspaceId: string, nodeId: string) => ipcRenderer.invoke('delete-node', accountId, workspaceId, nodeId),
+})
\ No newline at end of file
diff --git a/desktop/src/types/global.ts b/desktop/src/types/global.ts
new file mode 100644
index 00000000..ad7fb6af
--- /dev/null
+++ b/desktop/src/types/global.ts
@@ -0,0 +1,7 @@
+import {Account} from "@/types/accounts";
+import {Workspace} from "@/types/workspaces";
+
+export type GlobalDatabaseData = {
+ accounts: Account[];
+ workspaces: Workspace[];
+};
\ No newline at end of file
diff --git a/desktop/src/types/interface.d.ts b/desktop/src/types/interface.d.ts
deleted file mode 100644
index e39ed24d..00000000
--- a/desktop/src/types/interface.d.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import {Workspace} from "@/types/workspaces";
-import {Transaction} from "@/types/transactions";
-import {Account} from "@/types/accounts";
-import {Node} from "@/types/nodes";
-
-export interface GlobalDbApi {
- getAccounts: () => Promise<Account[]>
- addAccount: (account: Account) => Promise<void>
- getWorkspaces: () => Promise<Workspace[]>
- addWorkspace: (workspace: Workspace) => Promise<void>
- getNodes(): Promise<Node[]>
- enqueueTransaction: (transaction: Transaction) => Promise<void>
-}
-
-declare global {
- interface Window {
- globalDb: GlobalDbApi;
- }
-}
\ No newline at end of file
diff --git a/desktop/src/types/window.d.ts b/desktop/src/types/window.d.ts
new file mode 100644
index 00000000..5c6d5e91
--- /dev/null
+++ b/desktop/src/types/window.d.ts
@@ -0,0 +1,28 @@
+import {Workspace} from "@/types/workspaces";
+import {Transaction} from "@/types/transactions";
+import {Account} from "@/types/accounts";
+import {Node} from "@/types/nodes";
+import {GlobalDatabaseData} from "@/types/global";
+
+export interface GlobalDbApi {
+ init: () => Promise<GlobalDatabaseData>
+ getAccounts: () => Promise<Account[]>
+ addAccount: (account: Account) => Promise<void>
+ getWorkspaces: () => Promise<Workspace[]>
+ addWorkspace: (workspace: Workspace) => Promise<void>
+ addTransaction: (transaction: Transaction) => Promise<void>
+}
+
+export interface WorkspaceDbApi {
+ addNode: (accountId: string, workspaceId: string, node: Node) => Promise<void>
+ getNodes: (accountId: string, workspaceId: string) => Promise<Node[]>
+ updateNode: (accountId: string, workspaceId: string, node: Node) => Promise<void>
+ deleteNode: (accountId: string, workspaceId: string, nodeId: string) => Promise<void>
+}
+
+declare global {
+ interface Window {
+ globalDb: GlobalDbApi;
+ workspaceDb: WorkspaceDbApi;
+ }
+}
\ No newline at end of file