Skip to content

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

Treat users as entity on its own and not as a node

Hakan Shehu02a6ba486c54
diff --git a/apps/desktop/src/main/data/workspace/migrations.ts b/apps/desktop/src/main/data/workspace/migrations.ts
index 01fed804..18891a6f 100644
--- a/apps/desktop/src/main/data/workspace/migrations.ts
+++ b/apps/desktop/src/main/data/workspace/migrations.ts
@@ -1,5 +1,27 @@
import { Migration, sql } from 'kysely';
+const createUsersTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('users')
+ .addColumn('id', 'text', (col) => col.primaryKey().notNull())
+ .addColumn('email', 'text', (col) => col.notNull())
+ .addColumn('name', 'text', (col) => col.notNull())
+ .addColumn('avatar', 'text')
+ .addColumn('custom_name', 'text')
+ .addColumn('custom_avatar', 'text')
+ .addColumn('role', 'text', (col) => col.notNull())
+ .addColumn('status', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .addColumn('version', 'integer')
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('users').execute();
+ },
+};
+
const createNodesTable: Migration = {
up: async (db) => {
await db.schema
@@ -40,7 +62,6 @@ const createTransactionsTable: Migration = {
.createTable('transactions')
.addColumn('id', 'text', (col) => col.notNull().primaryKey())
.addColumn('node_id', 'text', (col) => col.notNull())
- .addColumn('node_type', 'text', (col) => col.notNull())
.addColumn('operation', 'text', (col) => col.notNull())
.addColumn('data', 'blob')
.addColumn('created_at', 'text', (col) => col.notNull())
@@ -118,7 +139,6 @@ const createInteractionsTable: Migration = {
.createTable('interactions')
.addColumn('user_id', 'text', (col) => col.notNull())
.addColumn('node_id', 'text', (col) => col.notNull())
- .addColumn('node_type', 'text', (col) => col.notNull())
.addColumn('attributes', 'text')
.addColumn('last_seen_at', 'text', (col) =>
col
@@ -148,7 +168,6 @@ const createInteractionEventsTable: Migration = {
await db.schema
.createTable('interaction_events')
.addColumn('node_id', 'text', (col) => col.notNull())
- .addColumn('node_type', 'text', (col) => col.notNull())
.addColumn('attribute', 'text', (col) => col.notNull())
.addColumn('value', 'text', (col) => col.notNull())
.addColumn('created_at', 'text', (col) => col.notNull())
@@ -270,15 +289,16 @@ const createCursorsTable: Migration = {
};
export const workspaceDatabaseMigrations: Record<string, Migration> = {
- '00001_create_nodes_table': createNodesTable,
- '00002_create_transactions_table': createTransactionsTable,
- '00003_create_collaborations_table': createCollaborationsTable,
- '00004_create_uploads_table': createUploadsTable,
- '00005_create_downloads_table': createDownloadsTable,
- '00006_create_interactions_table': createInteractionsTable,
- '00007_create_interaction_events_table': createInteractionEventsTable,
- '00008_create_node_paths_table': createNodePathsTable,
- '00009_create_node_names_table': createNodeNamesTable,
- '00010_create_node_texts_table': createNodeTextsTable,
- '00011_create_cursors_table': createCursorsTable,
+ '00001_create_users_table': createUsersTable,
+ '00002_create_nodes_table': createNodesTable,
+ '00003_create_transactions_table': createTransactionsTable,
+ '00004_create_collaborations_table': createCollaborationsTable,
+ '00005_create_uploads_table': createUploadsTable,
+ '00006_create_downloads_table': createDownloadsTable,
+ '00007_create_interactions_table': createInteractionsTable,
+ '00008_create_interaction_events_table': createInteractionEventsTable,
+ '00009_create_node_paths_table': createNodePathsTable,
+ '00010_create_node_names_table': createNodeNamesTable,
+ '00011_create_node_texts_table': createNodeTextsTable,
+ '00012_create_cursors_table': createCursorsTable,
};
diff --git a/apps/desktop/src/main/data/workspace/schema.ts b/apps/desktop/src/main/data/workspace/schema.ts
index ae61bf46..8f64f1b7 100644
--- a/apps/desktop/src/main/data/workspace/schema.ts
+++ b/apps/desktop/src/main/data/workspace/schema.ts
@@ -2,9 +2,28 @@ import {
InteractionAttribute,
NodeType,
SyncConsumerType,
+ WorkspaceRole,
} from '@colanode/core';
import { ColumnType, Insertable, Selectable, Updateable } from 'kysely';
+interface UserTable {
+ id: ColumnType<string, string, never>;
+ email: ColumnType<string, string, never>;
+ name: ColumnType<string, string, string>;
+ avatar: ColumnType<string | null, string | null, string | null>;
+ custom_name: ColumnType<string | null, string | null, string | null>;
+ custom_avatar: ColumnType<string | null, string | null, string | null>;
+ role: ColumnType<WorkspaceRole, WorkspaceRole, WorkspaceRole>;
+ status: ColumnType<string, string, never>;
+ created_at: ColumnType<string, string, never>;
+ updated_at: ColumnType<string | null, string | null, string | null>;
+ version: ColumnType<bigint, bigint, bigint>;
+}
+
+export type SelectUser = Selectable<UserTable>;
+export type CreateUser = Insertable<UserTable>;
+export type UpdateUser = Updateable<UserTable>;
+
interface NodeTable {
id: ColumnType<string, string, never>;
parent_id: ColumnType<string, never, never>;
@@ -32,7 +51,6 @@ export type SelectNodePath = Selectable<NodePathTable>;
interface TransactionTable {
id: ColumnType<string, string, never>;
node_id: ColumnType<string, string, never>;
- node_type: ColumnType<NodeType, NodeType, never>;
operation: ColumnType<string, string, never>;
data: ColumnType<Uint8Array | null, Uint8Array | null, never>;
created_at: ColumnType<string, string, never>;
@@ -89,7 +107,6 @@ export type UpdateDownload = Updateable<DownloadTable>;
interface InteractionTable {
user_id: ColumnType<string, string, never>;
node_id: ColumnType<string, string, never>;
- node_type: ColumnType<NodeType, NodeType, never>;
attributes: ColumnType<string, string, string>;
last_seen_at: ColumnType<string | null, string | null, string | null>;
last_opened_at: ColumnType<string | null, string | null, string | null>;
@@ -106,7 +123,6 @@ export type UpdateInteraction = Updateable<InteractionTable>;
interface InteractionEventTable {
node_id: ColumnType<string, string, never>;
- node_type: ColumnType<NodeType, NodeType, never>;
attribute: ColumnType<InteractionAttribute, string, string>;
value: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
@@ -145,6 +161,7 @@ interface CursorTable {
}
export interface WorkspaceDatabaseSchema {
+ users: UserTable;
nodes: NodeTable;
transactions: TransactionTable;
node_paths: NodePathTable;
diff --git a/apps/desktop/src/main/jobs/sync-pending-interactions.ts b/apps/desktop/src/main/jobs/sync-pending-interactions.ts
index 1878ec1a..dea30a44 100644
--- a/apps/desktop/src/main/jobs/sync-pending-interactions.ts
+++ b/apps/desktop/src/main/jobs/sync-pending-interactions.ts
@@ -103,7 +103,6 @@ export class SyncPendingInteractionsJobHandler
const message: SyncInteractionsMessage = {
type: 'sync_interactions',
nodeId,
- nodeType: firstEvent.node_type,
userId: credentials.userId,
events: events.map((e) => ({
attribute: e.attribute,
diff --git a/apps/desktop/src/main/mutations/index.ts b/apps/desktop/src/main/mutations/index.ts
index f5ea05cb..29a67b20 100644
--- a/apps/desktop/src/main/mutations/index.ts
+++ b/apps/desktop/src/main/mutations/index.ts
@@ -52,8 +52,8 @@ import { ViewUpdateMutationHandler } from '@/main/mutations/databases/view-updat
import { ViewNameUpdateMutationHandler } from '@/main/mutations/databases/view-name-update';
import { WorkspaceCreateMutationHandler } from '@/main/mutations/workspaces/workspace-create';
import { WorkspaceUpdateMutationHandler } from '@/main/mutations/workspaces/workspace-update';
-import { WorkspaceUserRoleUpdateMutationHandler } from '@/main/mutations/workspaces/workspace-user-role-update';
-import { WorkspaceUsersInviteMutationHandler } from '@/main/mutations/workspaces/workspace-users-invite';
+import { UserRoleUpdateMutationHandler } from '@/main/mutations/users/user-role-update';
+import { UsersInviteMutationHandler } from '@/main/mutations/users/users-invite';
import { MutationHandler } from '@/main/types';
import { MutationMap } from '@/shared/mutations';
@@ -98,8 +98,8 @@ export const mutationHandlerMap: MutationHandlerMap = {
server_create: new ServerCreateMutationHandler(),
space_create: new SpaceCreateMutationHandler(),
space_delete: new SpaceDeleteMutationHandler(),
- workspace_user_role_update: new WorkspaceUserRoleUpdateMutationHandler(),
- workspace_users_invite: new WorkspaceUsersInviteMutationHandler(),
+ user_role_update: new UserRoleUpdateMutationHandler(),
+ users_invite: new UsersInviteMutationHandler(),
workspace_create: new WorkspaceCreateMutationHandler(),
workspace_update: new WorkspaceUpdateMutationHandler(),
avatar_upload: new AvatarUploadMutationHandler(),
diff --git a/apps/desktop/src/main/mutations/interactions/mark-node-as-opened.ts b/apps/desktop/src/main/mutations/interactions/mark-node-as-opened.ts
index 8041a8ea..7b122251 100644
--- a/apps/desktop/src/main/mutations/interactions/mark-node-as-opened.ts
+++ b/apps/desktop/src/main/mutations/interactions/mark-node-as-opened.ts
@@ -11,33 +11,28 @@ export class MarkNodeAsOpenedMutationHandler
async handleMutation(
input: MarkNodeAsOpenedMutationInput
): Promise<MarkNodeAsOpenedMutationOutput> {
- await interactionService.setInteraction(
- input.userId,
- input.nodeId,
- input.nodeType,
- [
- {
- attribute: 'firstSeenAt',
- value: new Date().toISOString(),
- },
- {
- attribute: 'lastSeenAt',
- value: new Date().toISOString(),
- },
- {
- attribute: 'lastSeenTransactionId',
- value: input.transactionId,
- },
- {
- attribute: 'lastOpenedAt',
- value: new Date().toISOString(),
- },
- {
- attribute: 'lastOpenedTransactionId',
- value: input.transactionId,
- },
- ]
- );
+ await interactionService.setInteraction(input.userId, input.nodeId, [
+ {
+ attribute: 'firstSeenAt',
+ value: new Date().toISOString(),
+ },
+ {
+ attribute: 'lastSeenAt',
+ value: new Date().toISOString(),
+ },
+ {
+ attribute: 'lastSeenTransactionId',
+ value: input.transactionId,
+ },
+ {
+ attribute: 'lastOpenedAt',
+ value: new Date().toISOString(),
+ },
+ {
+ attribute: 'lastOpenedTransactionId',
+ value: input.transactionId,
+ },
+ ]);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/interactions/mark-node-as-seen.ts b/apps/desktop/src/main/mutations/interactions/mark-node-as-seen.ts
index 251c62fe..37229912 100644
--- a/apps/desktop/src/main/mutations/interactions/mark-node-as-seen.ts
+++ b/apps/desktop/src/main/mutations/interactions/mark-node-as-seen.ts
@@ -11,25 +11,20 @@ export class MarkNodeAsSeenMutationHandler
async handleMutation(
input: MarkNodeAsSeenMutationInput
): Promise<MarkNodeAsSeenMutationOutput> {
- await interactionService.setInteraction(
- input.userId,
- input.nodeId,
- input.nodeType,
- [
- {
- attribute: 'lastSeenAt',
- value: new Date().toISOString(),
- },
- {
- attribute: 'firstSeenAt',
- value: new Date().toISOString(),
- },
- {
- attribute: 'lastSeenTransactionId',
- value: input.transactionId,
- },
- ]
- );
+ await interactionService.setInteraction(input.userId, input.nodeId, [
+ {
+ attribute: 'lastSeenAt',
+ value: new Date().toISOString(),
+ },
+ {
+ attribute: 'firstSeenAt',
+ value: new Date().toISOString(),
+ },
+ {
+ attribute: 'lastSeenTransactionId',
+ value: input.transactionId,
+ },
+ ]);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/workspaces/workspace-user-role-update.ts b/apps/desktop/src/main/mutations/users/user-role-update.ts
similarity index 78%
rename from apps/desktop/src/main/mutations/workspaces/workspace-user-role-update.ts
rename to apps/desktop/src/main/mutations/users/user-role-update.ts
index 30bd7dbb..923ddd83 100644
--- a/apps/desktop/src/main/mutations/workspaces/workspace-user-role-update.ts
+++ b/apps/desktop/src/main/mutations/users/user-role-update.ts
@@ -1,20 +1,20 @@
-import { WorkspaceUserRoleUpdateOutput } from '@colanode/core';
+import { UserRoleUpdateOutput } from '@colanode/core';
import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import { httpClient } from '@/shared/lib/http-client';
import {
- WorkspaceUserRoleUpdateMutationInput,
- WorkspaceUserRoleUpdateMutationOutput,
+ UserRoleUpdateMutationInput,
+ UserRoleUpdateMutationOutput,
} from '@/shared/mutations/workspaces/workspace-user-role-update';
import { MutationError } from '@/shared/mutations';
-export class WorkspaceUserRoleUpdateMutationHandler
- implements MutationHandler<WorkspaceUserRoleUpdateMutationInput>
+export class UserRoleUpdateMutationHandler
+ implements MutationHandler<UserRoleUpdateMutationInput>
{
async handleMutation(
- input: WorkspaceUserRoleUpdateMutationInput
- ): Promise<WorkspaceUserRoleUpdateMutationOutput> {
+ input: UserRoleUpdateMutationInput
+ ): Promise<UserRoleUpdateMutationOutput> {
const workspace = await databaseService.appDatabase
.selectFrom('workspaces')
.selectAll()
@@ -51,7 +51,7 @@ export class WorkspaceUserRoleUpdateMutationHandler
);
}
- await httpClient.put<WorkspaceUserRoleUpdateOutput>(
+ await httpClient.put<UserRoleUpdateOutput>(
`/v1/workspaces/${workspace.workspace_id}/users/${input.userToUpdateId}`,
{
role: input.role,
diff --git a/apps/desktop/src/main/mutations/workspaces/workspace-users-invite.ts b/apps/desktop/src/main/mutations/users/users-invite.ts
similarity index 79%
rename from apps/desktop/src/main/mutations/workspaces/workspace-users-invite.ts
rename to apps/desktop/src/main/mutations/users/users-invite.ts
index b3f83c89..f95092e0 100644
--- a/apps/desktop/src/main/mutations/workspaces/workspace-users-invite.ts
+++ b/apps/desktop/src/main/mutations/users/users-invite.ts
@@ -1,20 +1,20 @@
-import { WorkspaceUsersInviteOutput } from '@colanode/core';
+import { UsersInviteOutput } from '@colanode/core';
import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import { httpClient } from '@/shared/lib/http-client';
import {
- WorkspaceUsersInviteMutationInput,
- WorkspaceUsersInviteMutationOutput,
+ UsersInviteMutationInput,
+ UsersInviteMutationOutput,
} from '@/shared/mutations/workspaces/workspace-users-invite';
import { MutationError } from '@/shared/mutations';
-export class WorkspaceUsersInviteMutationHandler
- implements MutationHandler<WorkspaceUsersInviteMutationInput>
+export class UsersInviteMutationHandler
+ implements MutationHandler<UsersInviteMutationInput>
{
async handleMutation(
- input: WorkspaceUsersInviteMutationInput
- ): Promise<WorkspaceUsersInviteMutationOutput> {
+ input: UsersInviteMutationInput
+ ): Promise<UsersInviteMutationOutput> {
const workspace = await databaseService.appDatabase
.selectFrom('workspaces')
.selectAll()
@@ -51,7 +51,7 @@ export class WorkspaceUsersInviteMutationHandler
);
}
- await httpClient.post<WorkspaceUsersInviteOutput>(
+ await httpClient.post<UsersInviteOutput>(
`/v1/workspaces/${workspace.workspace_id}/users`,
{
emails: input.emails,
diff --git a/apps/desktop/src/main/queries/index.ts b/apps/desktop/src/main/queries/index.ts
index 1656c2e6..24e2d63c 100644
--- a/apps/desktop/src/main/queries/index.ts
+++ b/apps/desktop/src/main/queries/index.ts
@@ -15,9 +15,10 @@ import { ServerListQueryHandler } from '@/main/queries/servers/server-list';
import { UserSearchQueryHandler } from '@/main/queries/users/user-search';
import { WorkspaceGetQueryHandler } from '@/main/queries/workspaces/workspace-get';
import { WorkspaceListQueryHandler } from '@/main/queries/workspaces/workspace-list';
-import { WorkspaceUserListQueryHandler } from '@/main/queries/workspaces/workspace-user-list';
+import { UserListQueryHandler } from '@/main/queries/users/user-list';
import { DatabaseListQueryHandler } from '@/main/queries/databases/database-list';
import { RecordSearchQueryHandler } from '@/main/queries/records/record-search';
+import { UserGetQueryHandler } from '@/main/queries/users/user-get';
import { QueryHandler } from '@/main/types';
import { QueryMap } from '@/shared/queries';
@@ -33,7 +34,7 @@ export const queryHandlerMap: QueryHandlerMap = {
server_list: new ServerListQueryHandler(),
user_search: new UserSearchQueryHandler(),
workspace_list: new WorkspaceListQueryHandler(),
- workspace_user_list: new WorkspaceUserListQueryHandler(),
+ user_list: new UserListQueryHandler(),
file_list: new FileListQueryHandler(),
emojis_get: new EmojisGetQueryHandler(),
icons_get: new IconsGetQueryHandler(),
@@ -46,4 +47,5 @@ export const queryHandlerMap: QueryHandlerMap = {
download_get: new DownloadGetQueryHandler(),
database_list: new DatabaseListQueryHandler(),
record_search: new RecordSearchQueryHandler(),
+ user_get: new UserGetQueryHandler(),
};
diff --git a/apps/desktop/src/main/queries/users/user-get.ts b/apps/desktop/src/main/queries/users/user-get.ts
new file mode 100644
index 00000000..0dd4478b
--- /dev/null
+++ b/apps/desktop/src/main/queries/users/user-get.ts
@@ -0,0 +1,83 @@
+import { databaseService } from '@/main/data/database-service';
+import { SelectUser } from '@/main/data/workspace/schema';
+import { ChangeCheckResult, QueryHandler } from '@/main/types';
+import { mapUser } from '@/main/utils';
+import { UserGetQueryInput } from '@/shared/queries/users/user-get';
+import { Event } from '@/shared/types/events';
+import { User } from '@/shared/types/users';
+
+export class UserGetQueryHandler implements QueryHandler<UserGetQueryInput> {
+ public async handleQuery(input: UserGetQueryInput): Promise<User | null> {
+ const row = await this.fetchUser(input);
+ return row ? mapUser(row) : null;
+ }
+
+ public async checkForChanges(
+ event: Event,
+ input: UserGetQueryInput,
+ _: User | null
+ ): Promise<ChangeCheckResult<UserGetQueryInput>> {
+ if (
+ event.type === 'workspace_deleted' &&
+ event.workspace.userId === input.userId
+ ) {
+ return {
+ hasChanges: true,
+ result: null,
+ };
+ }
+
+ if (
+ event.type === 'user_created' &&
+ event.userId === input.userId &&
+ event.user.id === input.id
+ ) {
+ return {
+ hasChanges: true,
+ result: event.user,
+ };
+ }
+
+ if (
+ event.type === 'user_updated' &&
+ event.userId === input.userId &&
+ event.user.id === input.id
+ ) {
+ return {
+ hasChanges: true,
+ result: event.user,
+ };
+ }
+
+ if (
+ event.type === 'user_deleted' &&
+ event.userId === input.userId &&
+ event.user.id === input.id
+ ) {
+ return {
+ hasChanges: true,
+ result: null,
+ };
+ }
+
+ return {
+ hasChanges: false,
+ };
+ }
+
+ private async fetchUser(
+ input: UserGetQueryInput
+ ): Promise<SelectUser | undefined> {
+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(
+ input.userId
+ );
+
+ const row = await workspaceDatabase
+ .selectFrom('users')
+ .selectAll()
+ .where('id', '=', input.id)
+ .executeTakeFirst();
+
+ return row;
+ }
+}
diff --git a/apps/desktop/src/main/queries/users/user-list.ts b/apps/desktop/src/main/queries/users/user-list.ts
new file mode 100644
index 00000000..741bb620
--- /dev/null
+++ b/apps/desktop/src/main/queries/users/user-list.ts
@@ -0,0 +1,89 @@
+import { databaseService } from '@/main/data/database-service';
+import { SelectUser } from '@/main/data/workspace/schema';
+import { ChangeCheckResult, QueryHandler } from '@/main/types';
+import { mapUser } from '@/main/utils';
+import { UserListQueryInput } from '@/shared/queries/users/user-list';
+import { Event } from '@/shared/types/events';
+import { User } from '@/shared/types/users';
+
+export class UserListQueryHandler implements QueryHandler<UserListQueryInput> {
+ public async handleQuery(input: UserListQueryInput): Promise<User[]> {
+ const rows = await this.fetchUsers(input);
+ return this.buildWorkspaceUserNodes(rows);
+ }
+
+ public async checkForChanges(
+ event: Event,
+ input: UserListQueryInput,
+ output: User[]
+ ): Promise<ChangeCheckResult<UserListQueryInput>> {
+ if (
+ event.type === 'workspace_deleted' &&
+ event.workspace.userId === input.userId
+ ) {
+ return {
+ hasChanges: true,
+ result: [],
+ };
+ }
+
+ if (event.type === 'user_created' && event.userId === input.userId) {
+ const newResult = await this.handleQuery(input);
+ return {
+ hasChanges: true,
+ result: newResult,
+ };
+ }
+
+ if (event.type === 'user_updated' && event.userId === input.userId) {
+ const user = output.find((user) => user.id === event.userId);
+ if (user) {
+ const newUsers = output.map((user) => {
+ if (user.id === event.user.id) {
+ return event.user;
+ }
+ return user;
+ });
+
+ return {
+ hasChanges: true,
+ result: newUsers,
+ };
+ }
+ }
+
+ if (event.type === 'user_deleted' && event.userId === input.userId) {
+ const newResult = await this.handleQuery(input);
+ return {
+ hasChanges: true,
+ result: newResult,
+ };
+ }
+
+ return {
+ hasChanges: false,
+ };
+ }
+
+ private async fetchUsers(input: UserListQueryInput): Promise<SelectUser[]> {
+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(
+ input.userId
+ );
+
+ const offset = (input.page - 1) * input.count;
+ const rows = await workspaceDatabase
+ .selectFrom('users')
+ .selectAll()
+ .orderBy('created_at asc')
+ .offset(offset)
+ .limit(input.count)
+ .execute();
+
+ return rows;
+ }
+
+ private buildWorkspaceUserNodes = (rows: SelectUser[]): User[] => {
+ const users = rows.map(mapUser);
+ return users;
+ };
+}
diff --git a/apps/desktop/src/main/queries/users/user-search.ts b/apps/desktop/src/main/queries/users/user-search.ts
index 6e096693..863031d3 100644
--- a/apps/desktop/src/main/queries/users/user-search.ts
+++ b/apps/desktop/src/main/queries/users/user-search.ts
@@ -1,17 +1,17 @@
-import { NodeTypes, UserNode } from '@colanode/core';
import { sql } from 'kysely';
import { databaseService } from '@/main/data/database-service';
-import { SelectNode } from '@/main/data/workspace/schema';
+import { SelectUser } from '@/main/data/workspace/schema';
import { ChangeCheckResult, QueryHandler } from '@/main/types';
-import { mapNode } from '@/main/utils';
+import { mapUser } from '@/main/utils';
import { UserSearchQueryInput } from '@/shared/queries/users/user-search';
import { Event } from '@/shared/types/events';
+import { User } from '@/shared/types/users';
export class UserSearchQueryHandler
implements QueryHandler<UserSearchQueryInput>
{
- public async handleQuery(input: UserSearchQueryInput): Promise<UserNode[]> {
+ public async handleQuery(input: UserSearchQueryInput): Promise<User[]> {
const rows =
input.searchQuery.length > 0
? await this.searchUsers(input)
@@ -23,7 +23,7 @@ export class UserSearchQueryHandler
public async checkForChanges(
event: Event,
input: UserSearchQueryInput,
- _: UserNode[]
+ _: User[]
): Promise<ChangeCheckResult<UserSearchQueryInput>> {
if (
event.type === 'workspace_deleted' &&
@@ -35,11 +35,7 @@ export class UserSearchQueryHandler
};
}
- if (
- event.type === 'node_created' &&
- event.userId === input.userId &&
- event.node.type === 'user'
- ) {
+ if (event.type === 'user_created' && event.userId === input.userId) {
const newResult = await this.handleQuery(input);
return {
hasChanges: true,
@@ -47,11 +43,7 @@ export class UserSearchQueryHandler
};
}
- if (
- event.type === 'node_updated' &&
- event.userId === input.userId &&
- event.node.type === 'user'
- ) {
+ if (event.type === 'user_updated' && event.userId === input.userId) {
const newResult = await this.handleQuery(input);
return {
hasChanges: true,
@@ -59,11 +51,7 @@ export class UserSearchQueryHandler
};
}
- if (
- event.type === 'node_deleted' &&
- event.userId === input.userId &&
- event.node.type === 'user'
- ) {
+ if (event.type === 'user_deleted' && event.userId === input.userId) {
const newResult = await this.handleQuery(input);
return {
hasChanges: true,
@@ -78,22 +66,21 @@ export class UserSearchQueryHandler
private async searchUsers(
input: UserSearchQueryInput
- ): Promise<SelectNode[]> {
+ ): Promise<SelectUser[]> {
const workspaceDatabase = await databaseService.getWorkspaceDatabase(
input.userId
);
const exclude = input.exclude ?? [];
- const query = sql<SelectNode>`
- SELECT n.*
- FROM nodes n
- JOIN node_names nn ON n.id = nn.id
- WHERE n.type = ${NodeTypes.User}
- AND n.id != ${input.userId}
+ const query = sql<SelectUser>`
+ SELECT u.*
+ FROM users u
+ JOIN node_names nn ON u.id = nn.id
+ WHERE u.id != ${input.userId}
AND nn.name MATCH ${input.searchQuery + '*'}
${
exclude.length > 0
- ? sql`AND n.id NOT IN (${sql.join(
+ ? sql`AND u.id NOT IN (${sql.join(
exclude.map((id) => sql`${id}`),
sql`, `
)})`
@@ -105,22 +92,21 @@ export class UserSearchQueryHandler
return result.rows;
}
- private async fetchUsers(input: UserSearchQueryInput): Promise<SelectNode[]> {
+ private async fetchUsers(input: UserSearchQueryInput): Promise<SelectUser[]> {
const workspaceDatabase = await databaseService.getWorkspaceDatabase(
input.userId
);
const exclude = input.exclude ?? [];
return workspaceDatabase
- .selectFrom('nodes')
- .where('type', '=', 'user')
+ .selectFrom('users')
.where('id', '!=', input.userId)
.where('id', 'not in', exclude)
.selectAll()
.execute();
}
- private buildUserNodes = (rows: SelectNode[]): UserNode[] => {
- return rows.map((row) => mapNode(row) as UserNode);
+ private buildUserNodes = (rows: SelectUser[]): User[] => {
+ return rows.map((row) => mapUser(row));
};
}
diff --git a/apps/desktop/src/main/queries/workspaces/workspace-user-list.ts b/apps/desktop/src/main/queries/workspaces/workspace-user-list.ts
deleted file mode 100644
index eb84d29f..00000000
--- a/apps/desktop/src/main/queries/workspaces/workspace-user-list.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { NodeTypes, UserNode } from '@colanode/core';
-
-import { databaseService } from '@/main/data/database-service';
-import { SelectNode } from '@/main/data/workspace/schema';
-import { ChangeCheckResult, QueryHandler } from '@/main/types';
-import { mapNode } from '@/main/utils';
-import { WorkspaceUserListQueryInput } from '@/shared/queries/workspaces/workspace-user-list';
-import { Event } from '@/shared/types/events';
-
-export class WorkspaceUserListQueryHandler
- implements QueryHandler<WorkspaceUserListQueryInput>
-{
- public async handleQuery(
- input: WorkspaceUserListQueryInput
- ): Promise<UserNode[]> {
- const rows = await this.fetchNodes(input);
- return this.buildWorkspaceUserNodes(rows);
- }
-
- public async checkForChanges(
- event: Event,
- input: WorkspaceUserListQueryInput,
- output: UserNode[]
- ): Promise<ChangeCheckResult<WorkspaceUserListQueryInput>> {
- if (
- event.type === 'workspace_deleted' &&
- event.workspace.userId === input.userId
- ) {
- return {
- hasChanges: true,
- result: [],
- };
- }
-
- if (
- event.type === 'node_created' &&
- event.userId === input.userId &&
- event.node.type === 'user'
- ) {
- const newResult = await this.handleQuery(input);
- return {
- hasChanges: true,
- result: newResult,
- };
- }
-
- if (
- event.type === 'node_updated' &&
- event.userId === input.userId &&
- event.node.type === 'user'
- ) {
- const user = output.find((user) => user.id === event.node.id);
- if (user) {
- const newUsers = output.map((user) => {
- if (user.id === event.node.id) {
- return event.node as UserNode;
- }
- return user;
- });
-
- return {
- hasChanges: true,
- result: newUsers,
- };
- }
- }
-
- if (
- event.type === 'node_deleted' &&
- event.userId === input.userId &&
- event.node.type === 'user'
- ) {
- const newResult = await this.handleQuery(input);
- return {
- hasChanges: true,
- result: newResult,
- };
- }
-
- return {
- hasChanges: false,
- };
- }
-
- private async fetchNodes(
- input: WorkspaceUserListQueryInput
- ): Promise<SelectNode[]> {
- const workspaceDatabase = await databaseService.getWorkspaceDatabase(
- input.userId
- );
-
- const offset = (input.page - 1) * input.count;
- const rows = await workspaceDatabase
- .selectFrom('nodes')
- .selectAll()
- .where('type', '=', 'user')
- .orderBy('created_at asc')
- .offset(offset)
- .limit(input.count)
- .execute();
-
- return rows;
- }
-
- private buildWorkspaceUserNodes = (rows: SelectNode[]): UserNode[] => {
- const nodes = rows.map(mapNode);
- const users: UserNode[] = [];
-
- for (const node of nodes) {
- if (node.type === NodeTypes.User) {
- users.push(node as UserNode);
- }
- }
-
- return users;
- };
-}
diff --git a/apps/desktop/src/main/services/interaction-service.ts b/apps/desktop/src/main/services/interaction-service.ts
index 0a545ad0..0495bafc 100644
--- a/apps/desktop/src/main/services/interaction-service.ts
+++ b/apps/desktop/src/main/services/interaction-service.ts
@@ -4,7 +4,6 @@ import {
InteractionAttribute,
InteractionAttributes,
mergeInteractionAttributes,
- NodeType,
ServerInteraction,
} from '@colanode/core';
import { sql } from 'kysely';
@@ -33,16 +32,10 @@ class InteractionService {
public async setInteraction(
userId: string,
nodeId: string,
- nodeType: NodeType,
input: UpdateInteractionInput | UpdateInteractionInput[]
) {
for (let i = 0; i < UPDATE_RETRIES_COUNT; i++) {
- const updated = await this.tryUpdateInteraction(
- userId,
- nodeId,
- nodeType,
- input
- );
+ const updated = await this.tryUpdateInteraction(userId, nodeId, input);
if (updated) {
return true;
@@ -55,7 +48,6 @@ class InteractionService {
private async tryUpdateInteraction(
userId: string,
nodeId: string,
- nodeType: NodeType,
input: UpdateInteractionInput | UpdateInteractionInput[]
): Promise<boolean> {
const workspaceDatabase =
@@ -91,7 +83,6 @@ class InteractionService {
eventsToCreate.push({
node_id: nodeId,
- node_type: nodeType,
attribute: input.attribute,
value: input.value,
created_at: new Date().toISOString(),
@@ -172,7 +163,6 @@ class InteractionService {
.returningAll()
.values({
node_id: nodeId,
- node_type: nodeType,
user_id: userId,
attributes: JSON.stringify(attributes),
created_at: new Date().toISOString(),
@@ -253,7 +243,6 @@ class InteractionService {
.values({
user_id: interaction.userId,
node_id: interaction.nodeId,
- node_type: interaction.nodeType,
attributes: JSON.stringify(interaction.attributes),
created_at: interaction.createdAt,
updated_at: interaction.updatedAt,
@@ -362,7 +351,6 @@ class InteractionService {
.values({
user_id: interaction.userId,
node_id: interaction.nodeId,
- node_type: interaction.nodeType,
attributes: JSON.stringify(attributes),
created_at: interaction.createdAt,
updated_at: interaction.updatedAt,
diff --git a/apps/desktop/src/main/services/node-service.ts b/apps/desktop/src/main/services/node-service.ts
index 9f3c0f8c..95f9cdf6 100644
--- a/apps/desktop/src/main/services/node-service.ts
+++ b/apps/desktop/src/main/services/node-service.ts
@@ -153,7 +153,6 @@ class NodeService {
id: transactionId,
node_id: inputItem.id,
operation: 'create',
- node_type: inputItem.attributes.type,
data: update,
created_at: createdAt,
created_by: context.userId,
@@ -238,7 +237,6 @@ class NodeService {
await interactionService.setInteraction(
userId,
createdTransaction.node_id,
- createdTransaction.node_type,
{
attribute: 'lastReceivedTransactionId',
value: createdTransaction.id,
@@ -374,7 +372,6 @@ class NodeService {
.values({
id: transactionId,
node_id: nodeId,
- node_type: node.type,
operation: 'update',
data: update,
created_at: updatedAt,
@@ -443,7 +440,6 @@ class NodeService {
await interactionService.setInteraction(
userId,
createdTransaction.node_id,
- createdTransaction.node_type,
{
attribute: 'lastReceivedTransactionId',
value: createdTransaction.id,
@@ -528,7 +524,6 @@ class NodeService {
.values({
id: generateId(IdType.Transaction),
node_id: nodeId,
- node_type: node.type,
operation: 'delete',
data: null,
created_at: new Date().toISOString(),
@@ -638,12 +633,12 @@ class NodeService {
ydoc.applyUpdate(transaction.data);
}
- const model = registry.getModel(firstTransaction.nodeType);
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ const model = registry.getModel(attributes.type);
if (!model) {
return false;
}
- const attributes = ydoc.getAttributes<NodeAttributes>();
const attributesJson = JSON.stringify(attributes);
const name = model.getName(nodeId, attributes);
const text = model.getText(nodeId, attributes);
@@ -692,7 +687,6 @@ class NodeService {
transactions.map((t) => ({
id: t.id,
node_id: t.nodeId,
- node_type: t.nodeType,
operation: t.operation,
data:
t.operation !== 'delete' && t.data
@@ -778,7 +772,6 @@ class NodeService {
transactions.map((t) => ({
id: t.id,
node_id: t.nodeId,
- node_type: t.nodeType,
operation: t.operation,
data:
t.operation !== 'delete' && t.data ? decodeState(t.data) : null,
@@ -869,15 +862,15 @@ class NodeService {
return;
}
- const model = registry.getModel(transaction.nodeType);
+ const ydoc = new YDoc();
+ ydoc.applyUpdate(transaction.data);
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+
+ const model = registry.getModel(attributes.type);
if (!model) {
return;
}
- const ydoc = new YDoc();
- ydoc.applyUpdate(transaction.data);
-
- const attributes = ydoc.getAttributes<NodeAttributes>();
const name = model.getName(transaction.nodeId, attributes);
const text = model.getText(transaction.nodeId, attributes);
@@ -901,7 +894,6 @@ class NodeService {
.values({
id: transaction.id,
node_id: transaction.nodeId,
- node_type: transaction.nodeType,
operation: 'create',
data: decodeState(transaction.data),
created_at: transaction.createdAt,
@@ -941,15 +933,10 @@ class NodeService {
node: mapNode(createdNode),
});
- await interactionService.setInteraction(
- userId,
- createdNode.id,
- createdNode.type,
- {
- attribute: 'lastReceivedTransactionId',
- value: transaction.id,
- }
- );
+ await interactionService.setInteraction(userId, createdNode.id, {
+ attribute: 'lastReceivedTransactionId',
+ value: transaction.id,
+ });
} else {
this.debug(
`Server create transaction ${transaction.id} for node ${transaction.nodeId} is incomplete`
@@ -1005,7 +992,7 @@ class NodeService {
return;
}
- const model = registry.getModel(transaction.nodeType);
+ const model = registry.getModel(transaction.nodeId);
if (!model) {
return;
}
@@ -1051,7 +1038,6 @@ class NodeService {
.values({
id: transaction.id,
node_id: transaction.nodeId,
- node_type: transaction.nodeType,
operation: 'update',
data: decodeState(transaction.data),
created_at: transaction.createdAt,
@@ -1105,15 +1091,10 @@ class NodeService {
node: mapNode(updatedNode),
});
- await interactionService.setInteraction(
- userId,
- updatedNode.id,
- updatedNode.type,
- {
- attribute: 'lastReceivedTransactionId',
- value: transaction.id,
- }
- );
+ await interactionService.setInteraction(userId, updatedNode.id, {
+ attribute: 'lastReceivedTransactionId',
+ value: transaction.id,
+ });
} else {
this.debug(
`Server update transaction ${transaction.id} for node ${transaction.nodeId} is incomplete`
@@ -1313,7 +1294,7 @@ class NodeService {
.orderBy('id', 'asc')
.execute();
- const model = registry.getModel(transaction.nodeType);
+ const model = registry.getModel(node.type);
if (!model) {
return true;
}
diff --git a/apps/desktop/src/main/services/radar-service.ts b/apps/desktop/src/main/services/radar-service.ts
index 6f7c419e..d45c5295 100644
--- a/apps/desktop/src/main/services/radar-service.ts
+++ b/apps/desktop/src/main/services/radar-service.ts
@@ -126,8 +126,7 @@ class RadarWorkspace {
const interaction = event.interaction;
if (
event.userId !== this.workspace.userId ||
- interaction.userId !== this.workspace.userId ||
- interaction.nodeType !== 'message'
+ interaction.userId !== this.workspace.userId
) {
return;
}
diff --git a/apps/desktop/src/main/services/socket-connection.ts b/apps/desktop/src/main/services/socket-connection.ts
index 2d0ec0e7..931196e7 100644
--- a/apps/desktop/src/main/services/socket-connection.ts
+++ b/apps/desktop/src/main/services/socket-connection.ts
@@ -66,6 +66,8 @@ export class SocketConnection {
syncService.syncServerCollaborations(message);
} else if (message.type === 'interactions_batch') {
syncService.syncServerInteractions(message);
+ } else if (message.type === 'users_batch') {
+ syncService.syncServerUsers(message);
} else if (message.type === 'account_updated') {
scheduler.trigger({
type: 'sync_account',
@@ -76,11 +78,6 @@ export class SocketConnection {
type: 'sync_account',
accountId: this.account.id,
});
- } else if (message.type === 'workspace_user_created') {
- scheduler.trigger({
- type: 'sync_account',
- accountId: this.account.id,
- });
} else if (message.type === 'workspace_deleted') {
scheduler.trigger({
type: 'sync_account',
diff --git a/apps/desktop/src/main/services/sync-consumer.ts b/apps/desktop/src/main/services/sync-consumer.ts
index a9ccd20d..1cd3f2fd 100644
--- a/apps/desktop/src/main/services/sync-consumer.ts
+++ b/apps/desktop/src/main/services/sync-consumer.ts
@@ -5,8 +5,11 @@ import {
InteractionsBatchMessage,
SyncConsumerType,
TransactionsBatchMessage,
+ UsersBatchMessage,
} from '@colanode/core';
+import { userService } from './user-service';
+
import { interactionService } from '@/main/services/interaction-service';
import { nodeService } from '@/main/services/node-service';
import { collaborationService } from '@/main/services/collaboration-service';
@@ -250,6 +253,45 @@ export class SyncConsumer {
}
}
+ public async syncUsers(message: UsersBatchMessage) {
+ if (this.type !== 'users') {
+ this.debug(
+ `Syncing of server users not supported for consumer type ${this.type}, skipping`
+ );
+ return;
+ }
+
+ this.debug(`Syncing server users for user ${message.userId}`);
+
+ this.status = 'syncing';
+ let cursor: bigint | null = null;
+ try {
+ for (const user of message.users) {
+ await userService.syncServerUser(message.userId, user);
+ cursor = BigInt(user.version);
+ }
+ } catch (error) {
+ this.debug(
+ error,
+ `Error syncing server users for user ${message.userId}`
+ );
+ } finally {
+ this.debug(
+ `Syncing of server users completed for user ${message.userId}`
+ );
+
+ if (cursor) {
+ await updateCursor(message.userId, 'users', cursor);
+ this.cursor = cursor;
+ this.status = 'idle';
+ this.initConsumer(cursor);
+ } else {
+ this.status = 'idle';
+ this.ping();
+ }
+ }
+ }
+
private initConsumer(cursor: bigint) {
const message: InitSyncConsumerMessage = {
type: 'init_sync_consumer',
diff --git a/apps/desktop/src/main/services/sync-service.ts b/apps/desktop/src/main/services/sync-service.ts
index c8341289..112f0ca2 100644
--- a/apps/desktop/src/main/services/sync-service.ts
+++ b/apps/desktop/src/main/services/sync-service.ts
@@ -4,6 +4,7 @@ import {
InteractionsBatchMessage,
SyncConsumerType,
TransactionsBatchMessage,
+ UsersBatchMessage,
} from '@colanode/core';
import { SyncConsumer } from '@/main/services/sync-consumer';
@@ -18,6 +19,7 @@ class SyncService {
await this.createConsumer(accountId, userId, 'deleted_collaborations');
await this.createConsumer(accountId, userId, 'collaborations');
await this.createConsumer(accountId, userId, 'interactions');
+ await this.createConsumer(accountId, userId, 'users');
}
public async deleteUserConsumers(userId: string) {
@@ -87,6 +89,15 @@ class SyncService {
}
}
+ public async syncServerUsers(message: UsersBatchMessage) {
+ const consumer = this.consumers.get(
+ this.getConsumerKey(message.userId, 'users')
+ );
+ if (consumer) {
+ consumer.syncUsers(message);
+ }
+ }
+
private getConsumerKey(userId: string, type: SyncConsumerType) {
return `${userId}-${type}`;
}
diff --git a/apps/desktop/src/main/services/user-service.ts b/apps/desktop/src/main/services/user-service.ts
new file mode 100644
index 00000000..be1dc5af
--- /dev/null
+++ b/apps/desktop/src/main/services/user-service.ts
@@ -0,0 +1,43 @@
+import { ServerUser } from '@colanode/core';
+
+import { databaseService } from '../data/database-service';
+
+class UserService {
+ public async syncServerUser(userId: string, user: ServerUser) {
+ const workspaceDatabase =
+ await databaseService.getWorkspaceDatabase(userId);
+
+ await workspaceDatabase
+ .insertInto('users')
+ .values({
+ id: user.id,
+ email: user.email,
+ name: user.name,
+ avatar: user.avatar,
+ role: user.role,
+ version: BigInt(user.version),
+ created_at: user.createdAt,
+ updated_at: user.updatedAt,
+ status: 'active',
+ custom_name: user.customName,
+ custom_avatar: user.customAvatar,
+ })
+ .onConflict((oc) =>
+ oc
+ .columns(['id'])
+ .doUpdateSet({
+ name: user.name,
+ avatar: user.avatar,
+ custom_name: user.customName,
+ custom_avatar: user.customAvatar,
+ role: user.role,
+ version: BigInt(user.version),
+ updated_at: user.updatedAt,
+ })
+ .where('version', '<', BigInt(user.version))
+ )
+ .execute();
+ }
+}
+
+export const userService = new UserService();
diff --git a/apps/desktop/src/main/utils.ts b/apps/desktop/src/main/utils.ts
index 6be915e3..99cfecc9 100644
--- a/apps/desktop/src/main/utils.ts
+++ b/apps/desktop/src/main/utils.ts
@@ -24,12 +24,14 @@ import {
SelectNode,
SelectTransaction,
SelectUpload,
+ SelectUser,
WorkspaceDatabaseSchema,
} from '@/main/data/workspace/schema';
import { Account } from '@/shared/types/accounts';
import { Interaction } from '@/shared/types/interactions';
import { Download, Upload } from '@/shared/types/nodes';
import { Server } from '@/shared/types/servers';
+import { User } from '@/shared/types/users';
import { Workspace, WorkspaceCredentials } from '@/shared/types/workspaces';
export const appPath = app.getPath('userData');
@@ -99,7 +101,6 @@ export const fetchNodeAncestors = (
.select('ancestor_id')
.where('descendant_id', '=', nodeId)
)
- .where('type', '!=', 'workspace')
.execute();
};
@@ -173,6 +174,20 @@ export const fetchCursor = async (
return cursor?.value ?? 0n;
};
+export const mapUser = (row: SelectUser): User => {
+ return {
+ id: row.id,
+ email: row.email,
+ name: row.name,
+ avatar: row.avatar,
+ customName: row.custom_name,
+ customAvatar: row.custom_avatar,
+ role: row.role,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+};
+
export const mapNode = (row: SelectNode): Node => {
return {
id: row.id,
@@ -218,7 +233,6 @@ export const mapTransaction = (row: SelectTransaction): LocalTransaction => {
return {
id: row.id,
nodeId: row.node_id,
- nodeType: row.node_type,
operation: 'create',
data: encodeState(row.data),
createdAt: row.created_at,
@@ -230,7 +244,6 @@ export const mapTransaction = (row: SelectTransaction): LocalTransaction => {
return {
id: row.id,
nodeId: row.node_id,
- nodeType: row.node_type,
operation: 'update',
data: encodeState(row.data),
createdAt: row.created_at,
@@ -242,7 +255,6 @@ export const mapTransaction = (row: SelectTransaction): LocalTransaction => {
return {
id: row.id,
nodeId: row.node_id,
- nodeType: row.node_type,
operation: 'delete',
createdAt: row.created_at,
createdBy: row.created_by,
@@ -289,7 +301,6 @@ export const mapInteraction = (row: SelectInteraction): Interaction => {
return {
userId: row.user_id,
nodeId: row.node_id,
- nodeType: row.node_type,
attributes: JSON.parse(row.attributes),
createdAt: new Date(row.created_at),
updatedAt: row.updated_at ? new Date(row.updated_at) : null,
diff --git a/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx
index 3a6b2436..c7adf147 100644
--- a/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx
@@ -10,30 +10,25 @@ interface ChatBreadcrumbItemProps {
export const ChatBreadcrumbItem = ({ node }: ChatBreadcrumbItemProps) => {
const workspace = useWorkspace();
- const collaboratorId =
+ const userId =
Object.keys(node.attributes.collaborators).find(
(id) => id !== workspace.userId
) ?? '';
const { data, isPending } = useQuery({
- type: 'node_get',
- nodeId: collaboratorId,
+ type: 'user_get',
+ id: userId,
userId: workspace.userId,
});
- if (isPending || !data || data.type !== 'user') {
+ if (isPending || !data) {
return null;
}
return (
<div className="flex items-center space-x-2">
- <Avatar
- size="small"
- id={data.id}
- name={data.attributes.name}
- avatar={data.attributes.avatar}
- />
- <span>{data.attributes.name}</span>
+ <Avatar size="small" id={data.id} name={data.name} avatar={data.avatar} />
+ <span>{data.name}</span>
</div>
);
};
diff --git a/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx b/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx
index d719cc78..a2cc9ead 100644
--- a/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx
@@ -16,18 +16,18 @@ export const ChatSidebarItem = ({ node }: ChatSidebarItemProps) => {
const workspace = useWorkspace();
const radar = useRadar();
- const collaboratorId =
+ const userId =
Object.keys(node.attributes.collaborators).find(
(id) => id !== workspace.userId
) ?? '';
const { data, isPending } = useQuery({
- type: 'node_get',
- nodeId: collaboratorId,
+ type: 'user_get',
+ id: userId,
userId: workspace.userId,
});
- if (isPending || !data || data.type !== 'user') {
+ if (isPending || !data) {
return null;
}
@@ -56,8 +56,8 @@ export const ChatSidebarItem = ({ node }: ChatSidebarItemProps) => {
>
<Avatar
id={data.id}
- avatar={data.attributes.avatar}
- name={data.attributes.name}
+ avatar={data.avatar}
+ name={data.name}
className="h-5 w-5"
/>
<span
@@ -66,7 +66,7 @@ export const ChatSidebarItem = ({ node }: ChatSidebarItemProps) => {
!isActive && unreadCount > 0 && 'font-semibold'
)}
>
- {data.attributes.name ?? 'Unnamed'}
+ {data.name ?? 'Unnamed'}
</span>
{!isActive && (
<ReadStateIndicator count={unreadCount} hasChanges={unreadCount > 0} />
diff --git a/apps/desktop/src/renderer/components/collaborators/node-collaborator-audit.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborator-audit.tsx
index 16e0c429..8983fb75 100644
--- a/apps/desktop/src/renderer/components/collaborators/node-collaborator-audit.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborator-audit.tsx
@@ -15,12 +15,12 @@ export const NodeCollaboratorAudit = ({
}: NodeCollaboratorAuditProps) => {
const workspace = useWorkspace();
const { data, isPending } = useQuery({
- type: 'node_get',
- nodeId: collaboratorId,
+ type: 'user_get',
+ id: collaboratorId,
userId: workspace.userId,
});
- if (isPending || !data || data.type !== 'user') {
+ if (isPending || !data) {
return null;
}
@@ -28,12 +28,12 @@ export const NodeCollaboratorAudit = ({
<div className="flex items-center gap-2 w-full">
<Avatar
id={data.id}
- name={data.attributes.name}
- avatar={data.attributes.avatar}
+ name={data.name}
+ avatar={data.avatar}
className="size-7"
/>
<div className="flex flex-col">
- <span className="font-normal flex-grow">{data.attributes.name}</span>
+ <span className="font-normal flex-grow">{data.name}</span>
<span className="text-xs text-muted-foreground">{timeAgo(date)}</span>
</div>
</div>
diff --git a/apps/desktop/src/renderer/components/collaborators/node-collaborator-create.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborator-create.tsx
index 4fd4482b..5bf87790 100644
--- a/apps/desktop/src/renderer/components/collaborators/node-collaborator-create.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborator-create.tsx
@@ -1,6 +1,6 @@
-import { UserNode } from '@colanode/core';
import React from 'react';
+import { User } from '@/shared/types/users';
import { NodeCollaboratorRoleDropdown } from '@/renderer/components/collaborators/node-collaborator-role-dropdown';
import { NodeCollaboratorSearch } from '@/renderer/components/collaborators/node-collaborator-search';
import { Button } from '@/renderer/components/ui/button';
@@ -21,7 +21,7 @@ export const NodeCollaboratorCreate = ({
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- const [users, setUsers] = React.useState<UserNode[]>([]);
+ const [users, setUsers] = React.useState<User[]>([]);
const [role, setRole] = React.useState('collaborator');
return (
diff --git a/apps/desktop/src/renderer/components/collaborators/node-collaborator-search.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborator-search.tsx
index 2ecf8206..126b3b2e 100644
--- a/apps/desktop/src/renderer/components/collaborators/node-collaborator-search.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborator-search.tsx
@@ -1,7 +1,7 @@
-import { UserNode } from '@colanode/core';
import { X } from 'lucide-react';
import React from 'react';
+import { User } from '@/shared/types/users';
import { Avatar } from '@/renderer/components/avatars/avatar';
import { Badge } from '@/renderer/components/ui/badge';
import { Button } from '@/renderer/components/ui/button';
@@ -23,8 +23,8 @@ import { useQuery } from '@/renderer/hooks/use-query';
interface NodeCollaboratorSearchProps {
excluded: string[];
- value: UserNode[];
- onChange: (value: UserNode[]) => void;
+ value: User[];
+ onChange: (value: User[]) => void;
}
export const NodeCollaboratorSearch = ({
@@ -57,7 +57,7 @@ export const NodeCollaboratorSearch = ({
>
{value.map((user) => (
<Badge key={user.id} variant="outline">
- {user.attributes.name}
+ {user.name}
<span
className="ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
onClick={(e) => {
@@ -99,14 +99,14 @@ export const NodeCollaboratorSearch = ({
<div className="flex w-full flex-row items-center gap-2">
<Avatar
id={user.id}
- name={user.attributes.name}
- avatar={user.attributes.avatar}
+ name={user.name}
+ avatar={user.avatar}
className="h-7 w-7"
/>
<div className="flex flex-grow flex-col">
- <p className="text-sm">{user.attributes.name}</p>
+ <p className="text-sm">{user.name}</p>
<p className="text-xs text-muted-foreground">
- {user.attributes.email}
+ {user.email}
</p>
</div>
</div>
diff --git a/apps/desktop/src/renderer/components/collaborators/node-collaborator.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborator.tsx
index 8288db5a..725db1d1 100644
--- a/apps/desktop/src/renderer/components/collaborators/node-collaborator.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborator.tsx
@@ -27,30 +27,22 @@ export const NodeCollaborator = ({
const { mutate } = useMutation();
const { data } = useQuery({
- type: 'node_get',
- nodeId: collaboratorId,
+ type: 'user_get',
+ id: collaboratorId,
userId: workspace.userId,
});
- if (!data || data.type !== 'user') {
+ if (!data) {
return null;
}
return (
<div className="flex items-center justify-between space-x-3">
<div className="flex items-center space-x-3">
- <Avatar
- id={data.id}
- name={data.attributes.name}
- avatar={data.attributes.avatar}
- />
+ <Avatar id={data.id} name={data.name} avatar={data.avatar} />
<div className="flex-grow">
- <p className="text-sm font-medium leading-none">
- {data.attributes.name}
- </p>
- <p className="text-sm text-muted-foreground">
- {data.attributes.email}
- </p>
+ <p className="text-sm font-medium leading-none">{data.name}</p>
+ <p className="text-sm text-muted-foreground">{data.email}</p>
</div>
</div>
<div className="flex flex-row items-center gap-1">
diff --git a/apps/desktop/src/renderer/components/files/file-sidebar.tsx b/apps/desktop/src/renderer/components/files/file-sidebar.tsx
index 6cb28769..18fa0daf 100644
--- a/apps/desktop/src/renderer/components/files/file-sidebar.tsx
+++ b/apps/desktop/src/renderer/components/files/file-sidebar.tsx
@@ -23,12 +23,12 @@ const FileMeta = ({ title, value }: { title: string; value: string }) => {
export const FileSidebar = ({ file }: FileSidebarProps) => {
const workspace = useWorkspace();
const { data } = useQuery({
- type: 'node_get',
- nodeId: file.createdBy,
+ type: 'user_get',
+ id: file.createdBy,
userId: workspace.userId,
});
- const user = data?.type === 'user' ? data : null;
+ const user = data ?? null;
return (
<React.Fragment>
@@ -57,11 +57,11 @@ export const FileSidebar = ({ file }: FileSidebarProps) => {
<div className="mt-1 flex flex-row items-center gap-2">
<Avatar
id={user.id}
- name={user.attributes.name}
- avatar={user.attributes.avatar}
+ name={user.name}
+ avatar={user.avatar}
className="h-8 w-8"
/>
- <p className="text-foreground/80">{user.attributes.name}</p>
+ <p className="text-foreground/80">{user.name}</p>
</div>
</div>
)}
diff --git a/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx b/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx
index c9a489b8..853d67e9 100644
--- a/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx
@@ -1,4 +1,4 @@
-import { MessageNode, UserNode } from '@colanode/core';
+import { MessageNode } from '@colanode/core';
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
@@ -15,22 +15,20 @@ export const MessageAuthorAvatar = ({
}: MessageAuthorAvatarProps) => {
const workspace = useWorkspace();
const { data } = useQuery({
- type: 'node_get',
- nodeId: message.createdBy,
+ type: 'user_get',
+ id: message.createdBy,
userId: workspace.userId,
});
- if (!data || data.type !== 'user') {
+ if (!data) {
return null;
}
- const author = data as UserNode;
-
return (
<Avatar
- id={author.id}
- name={author.attributes.name}
- avatar={author.attributes.avatar}
+ id={data.id}
+ name={data.name}
+ avatar={data.avatar}
size="medium"
className={className}
/>
diff --git a/apps/desktop/src/renderer/components/messages/message-author-name.tsx b/apps/desktop/src/renderer/components/messages/message-author-name.tsx
index 1e16f52c..42349e8e 100644
--- a/apps/desktop/src/renderer/components/messages/message-author-name.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-author-name.tsx
@@ -1,4 +1,4 @@
-import { MessageNode, UserNode } from '@colanode/core';
+import { MessageNode } from '@colanode/core';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
@@ -15,20 +15,14 @@ export const MessageAuthorName = ({
}: MessageAuthorNameProps) => {
const workspace = useWorkspace();
const { data } = useQuery({
- type: 'node_get',
- nodeId: message.createdBy,
+ type: 'user_get',
+ id: message.createdBy,
userId: workspace.userId,
});
- if (!data || data.type !== 'user') {
+ if (!data) {
return null;
}
- const author = data as UserNode;
-
- return (
- <span className={cn('font-medium', className)}>
- {author.attributes.name}
- </span>
- );
+ return <span className={cn('font-medium', className)}>{data.name}</span>;
};
diff --git a/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx b/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx
index 219e6fcf..eaae4f98 100644
--- a/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx
@@ -15,20 +15,19 @@ export const MessageReplyBanner = ({
}: MessageReplyBannerProps) => {
const workspace = useWorkspace();
const { data } = useQuery({
- type: 'node_get',
- nodeId: message.createdBy,
+ type: 'user_get',
+ id: message.createdBy,
userId: workspace.userId,
});
- if (!data || data.type !== 'user') {
+ if (!data) {
return null;
}
return (
<div className="flex flex-row items-center justify-between rounded-t-lg border-b-2 bg-gray-100 p-2 text-foreground">
<p className="text-sm">
- Replying to{' '}
- <span className="font-semibold">{data.attributes.name}</span>
+ Replying to <span className="font-semibold">{data.name}</span>
</p>
<button className="cursor-pointer" onClick={onCancel}>
<CircleX className="size-4" />
diff --git a/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx b/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx
index 81179635..26b5a4f7 100644
--- a/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx
@@ -1,4 +1,4 @@
-import { CollaboratorFieldAttributes, UserNode } from '@colanode/core';
+import { CollaboratorFieldAttributes } from '@colanode/core';
import { X } from 'lucide-react';
import React from 'react';
@@ -14,22 +14,23 @@ import { UserSearch } from '@/renderer/components/users/user-search';
import { useRecord } from '@/renderer/contexts/record';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQueries } from '@/renderer/hooks/use-queries';
+import { User } from '@/shared/types/users';
interface RecordCollaboratorValueProps {
field: CollaboratorFieldAttributes;
readOnly?: boolean;
}
-const CollaboratorBadge = ({ collaborator }: { collaborator: UserNode }) => {
+const CollaboratorBadge = ({ collaborator }: { collaborator: User }) => {
return (
<div className="flex flex-row items-center gap-1 text-sm">
<Avatar
id={collaborator.id}
- name={collaborator.attributes.name}
- avatar={collaborator.attributes.avatar}
+ name={collaborator.name}
+ avatar={collaborator.avatar}
size="small"
/>
- <p>{collaborator.attributes.name}</p>
+ <p>{collaborator.name}</p>
</div>
);
};
@@ -46,15 +47,15 @@ export const RecordCollaboratorValue = ({
const collaboratorIds = record.getCollaboratorValue(field) ?? [];
const results = useQueries(
collaboratorIds.map((id) => ({
- type: 'node_get',
- nodeId: id,
+ type: 'user_get',
+ id,
userId: workspace.userId,
}))
);
- const collaborators: UserNode[] = [];
+ const collaborators: User[] = [];
for (const result of results) {
- if (result.data && result.data.type === 'user') {
+ if (result.data) {
collaborators.push(result.data);
}
}
@@ -91,14 +92,14 @@ export const RecordCollaboratorValue = ({
>
<Avatar
id={collaborator.id}
- name={collaborator.attributes.name}
- avatar={collaborator.attributes.avatar}
+ name={collaborator.name}
+ avatar={collaborator.avatar}
className="h-7 w-7"
/>
<div className="flex flex-grow flex-col">
- <p className="text-sm">{collaborator.attributes.name}</p>
+ <p className="text-sm">{collaborator.name}</p>
<p className="text-xs text-muted-foreground">
- {collaborator.attributes.email}
+ {collaborator.email}
</p>
</div>
{record.canEdit && !readOnly && (
diff --git a/apps/desktop/src/renderer/components/records/values/record-created-by-value.tsx b/apps/desktop/src/renderer/components/records/values/record-created-by-value.tsx
index 4256dbd5..29fa2b38 100644
--- a/apps/desktop/src/renderer/components/records/values/record-created-by-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-created-by-value.tsx
@@ -13,21 +13,20 @@ export const RecordCreatedByValue = ({ field }: RecordCreatedByValueProps) => {
const workspace = useWorkspace();
const record = useRecord();
const { data } = useQuery({
- type: 'node_get',
- nodeId: record.createdBy,
+ type: 'user_get',
+ id: record.createdBy,
userId: workspace.userId,
});
- const createdBy =
- data && data.attributes.type === 'user'
- ? {
- name: data.attributes.name,
- avatar: data.attributes.avatar,
- }
- : {
- name: 'Unknown',
- avatar: null,
- };
+ const createdBy = data
+ ? {
+ name: data.name,
+ avatar: data.avatar,
+ }
+ : {
+ name: 'Unknown',
+ avatar: null,
+ };
return (
<div
diff --git a/apps/desktop/src/renderer/components/records/values/record-updated-by-value.tsx b/apps/desktop/src/renderer/components/records/values/record-updated-by-value.tsx
index 31b25a2f..0e662fc2 100644
--- a/apps/desktop/src/renderer/components/records/values/record-updated-by-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-updated-by-value.tsx
@@ -16,8 +16,8 @@ export const RecordUpdatedByValue = ({ field }: RecordUpdatedByValueProps) => {
const { data } = useQuery(
{
- type: 'node_get',
- nodeId: record.updatedBy!,
+ type: 'user_get',
+ id: record.updatedBy!,
userId: workspace.userId,
},
{
@@ -25,13 +25,12 @@ export const RecordUpdatedByValue = ({ field }: RecordUpdatedByValueProps) => {
}
);
- const updatedBy =
- data && data.attributes.type === 'user'
- ? {
- name: data.attributes.name,
- avatar: data.attributes.avatar,
- }
- : null;
+ const updatedBy = data
+ ? {
+ name: data.name,
+ avatar: data.avatar,
+ }
+ : null;
return (
<div
diff --git a/apps/desktop/src/renderer/components/users/user-search.tsx b/apps/desktop/src/renderer/components/users/user-search.tsx
index 74d63957..532094c7 100644
--- a/apps/desktop/src/renderer/components/users/user-search.tsx
+++ b/apps/desktop/src/renderer/components/users/user-search.tsx
@@ -1,4 +1,3 @@
-import { UserNode } from '@colanode/core';
import React from 'react';
import { Avatar } from '@/renderer/components/avatars/avatar';
@@ -12,10 +11,11 @@ import {
} from '@/renderer/components/ui/command';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { User } from '@/shared/types/users';
interface UserSearchProps {
exclude?: string[];
- onSelect: (user: UserNode) => void;
+ onSelect: (user: User) => void;
}
export const UserSearch = ({ exclude, onSelect }: UserSearchProps) => {
@@ -51,15 +51,13 @@ export const UserSearch = ({ exclude, onSelect }: UserSearchProps) => {
<div className="flex w-full flex-row items-center gap-2">
<Avatar
id={user.id}
- name={user.attributes.name}
- avatar={user.attributes.avatar}
+ name={user.name}
+ avatar={user.avatar}
className="h-7 w-7"
/>
<div className="flex flex-grow flex-col">
- <p className="text-sm">{user.attributes.name}</p>
- <p className="text-xs text-muted-foreground">
- {user.attributes.email}
- </p>
+ <p className="text-sm">{user.name}</p>
+ <p className="text-xs text-muted-foreground">{user.email}</p>
</div>
</div>
</CommandItem>
diff --git a/apps/desktop/src/renderer/components/workspaces/workspace-user-invite.tsx b/apps/desktop/src/renderer/components/workspaces/workspace-user-invite.tsx
index fc522067..f2594f87 100644
--- a/apps/desktop/src/renderer/components/workspaces/workspace-user-invite.tsx
+++ b/apps/desktop/src/renderer/components/workspaces/workspace-user-invite.tsx
@@ -82,7 +82,7 @@ export const WorkspaceUserInvite = ({
mutate({
input: {
- type: 'workspace_users_invite',
+ type: 'users_invite',
emails: emails,
userId: workspace.userId,
role: 'collaborator',
diff --git a/apps/desktop/src/renderer/components/workspaces/workspace-user-role-dropdown.tsx b/apps/desktop/src/renderer/components/workspaces/workspace-user-role-dropdown.tsx
index 1ac5a1b2..d360baf4 100644
--- a/apps/desktop/src/renderer/components/workspaces/workspace-user-role-dropdown.tsx
+++ b/apps/desktop/src/renderer/components/workspaces/workspace-user-role-dropdown.tsx
@@ -102,7 +102,7 @@ export const WorkspaceUserRoleDropdown = ({
mutate({
input: {
- type: 'workspace_user_role_update',
+ type: 'user_role_update',
userToUpdateId: userId,
role: role.value,
userId: workspace.userId,
diff --git a/apps/desktop/src/renderer/components/workspaces/workspace-users.tsx b/apps/desktop/src/renderer/components/workspaces/workspace-users.tsx
index 098d9c31..a9441f72 100644
--- a/apps/desktop/src/renderer/components/workspaces/workspace-users.tsx
+++ b/apps/desktop/src/renderer/components/workspaces/workspace-users.tsx
@@ -9,7 +9,7 @@ import { WorkspaceUserInvite } from '@/renderer/components/workspaces/workspace-
import { WorkspaceUserRoleDropdown } from '@/renderer/components/workspaces/workspace-user-role-dropdown';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQueries } from '@/renderer/hooks/use-queries';
-import { WorkspaceUserListQueryInput } from '@/shared/queries/workspaces/workspace-user-list';
+import { UserListQueryInput } from '@/shared/queries/users/user-list';
const USERS_PER_PAGE = 50;
@@ -18,10 +18,10 @@ export const WorkspaceUsers = () => {
const canEditUsers = workspace.role === 'owner' || workspace.role === 'admin';
const [lastPage, setLastPage] = React.useState<number>(1);
- const inputs: WorkspaceUserListQueryInput[] = Array.from({
+ const inputs: UserListQueryInput[] = Array.from({
length: lastPage,
}).map((_, i) => ({
- type: 'workspace_user_list',
+ type: 'user_list',
page: i + 1,
count: USERS_PER_PAGE,
userId: workspace.userId,
@@ -48,10 +48,10 @@ export const WorkspaceUsers = () => {
</div>
<div className="flex flex-col gap-2">
{users.map((user) => {
- const name: string = user.attributes.name ?? 'Unknown';
- const email: string = user.attributes.email ?? ' ';
- const avatar: string | null | undefined = user.attributes.avatar;
- const role: WorkspaceRole = user.attributes.role;
+ const name: string = user.name ?? 'Unknown';
+ const email: string = user.email ?? ' ';
+ const avatar: string | null | undefined = user.avatar;
+ const role: WorkspaceRole = user.role;
if (!role) {
return null;
@@ -61,9 +61,7 @@ export const WorkspaceUsers = () => {
<div key={user.id} className="flex items-center space-x-3">
<Avatar id={user.id} name={name} avatar={avatar} />
<div className="flex-grow">
- <p className="text-sm font-medium leading-none">
- {user.attributes.name}
- </p>
+ <p className="text-sm font-medium leading-none">{name}</p>
<p className="text-sm text-muted-foreground">{email}</p>
</div>
<WorkspaceUserRoleDropdown
diff --git a/apps/desktop/src/shared/mutations/interactions/mark-node-as-opened.ts b/apps/desktop/src/shared/mutations/interactions/mark-node-as-opened.ts
index 62991043..35558779 100644
--- a/apps/desktop/src/shared/mutations/interactions/mark-node-as-opened.ts
+++ b/apps/desktop/src/shared/mutations/interactions/mark-node-as-opened.ts
@@ -1,10 +1,7 @@
-import { NodeType } from '@colanode/core';
-
export type MarkNodeAsOpenedMutationInput = {
type: 'mark_node_as_opened';
userId: string;
nodeId: string;
- nodeType: NodeType;
transactionId: string;
};
diff --git a/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts b/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts
index 2e1c5a72..949ce9aa 100644
--- a/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts
+++ b/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts
@@ -1,19 +1,19 @@
-export type WorkspaceUserRoleUpdateMutationInput = {
- type: 'workspace_user_role_update';
+export type UserRoleUpdateMutationInput = {
+ type: 'user_role_update';
userToUpdateId: string;
role: string;
userId: string;
};
-export type WorkspaceUserRoleUpdateMutationOutput = {
+export type UserRoleUpdateMutationOutput = {
success: boolean;
};
declare module '@/shared/mutations' {
interface MutationMap {
- workspace_user_role_update: {
- input: WorkspaceUserRoleUpdateMutationInput;
- output: WorkspaceUserRoleUpdateMutationOutput;
+ user_role_update: {
+ input: UserRoleUpdateMutationInput;
+ output: UserRoleUpdateMutationOutput;
};
}
}
diff --git a/apps/desktop/src/shared/mutations/workspaces/workspace-users-invite.ts b/apps/desktop/src/shared/mutations/workspaces/workspace-users-invite.ts
index b7116ee0..e2e3df35 100644
--- a/apps/desktop/src/shared/mutations/workspaces/workspace-users-invite.ts
+++ b/apps/desktop/src/shared/mutations/workspaces/workspace-users-invite.ts
@@ -1,21 +1,21 @@
import { WorkspaceRole } from '@colanode/core';
-export type WorkspaceUsersInviteMutationInput = {
- type: 'workspace_users_invite';
+export type UsersInviteMutationInput = {
+ type: 'users_invite';
emails: string[];
userId: string;
role: WorkspaceRole;
};
-export type WorkspaceUsersInviteMutationOutput = {
+export type UsersInviteMutationOutput = {
success: boolean;
};
declare module '@/shared/mutations' {
interface MutationMap {
- workspace_users_invite: {
- input: WorkspaceUsersInviteMutationInput;
- output: WorkspaceUsersInviteMutationOutput;
+ users_invite: {
+ input: UsersInviteMutationInput;
+ output: UsersInviteMutationOutput;
};
}
}
diff --git a/apps/desktop/src/shared/queries/users/user-get.ts b/apps/desktop/src/shared/queries/users/user-get.ts
new file mode 100644
index 00000000..a196dd21
--- /dev/null
+++ b/apps/desktop/src/shared/queries/users/user-get.ts
@@ -0,0 +1,16 @@
+import { User } from '@/shared/types/users';
+
+export type UserGetQueryInput = {
+ type: 'user_get';
+ id: string;
+ userId: string;
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ user_get: {
+ input: UserGetQueryInput;
+ output: User | null;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/users/user-list.ts b/apps/desktop/src/shared/queries/users/user-list.ts
new file mode 100644
index 00000000..4125b843
--- /dev/null
+++ b/apps/desktop/src/shared/queries/users/user-list.ts
@@ -0,0 +1,17 @@
+import { User } from '@/shared/types/users';
+
+export type UserListQueryInput = {
+ type: 'user_list';
+ userId: string;
+ page: number;
+ count: number;
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ user_list: {
+ input: UserListQueryInput;
+ output: User[];
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/users/user-search.ts b/apps/desktop/src/shared/queries/users/user-search.ts
index beadcf64..87d1bfb6 100644
--- a/apps/desktop/src/shared/queries/users/user-search.ts
+++ b/apps/desktop/src/shared/queries/users/user-search.ts
@@ -1,4 +1,4 @@
-import { UserNode } from '@colanode/core';
+import { User } from '@/shared/types/users';
export type UserSearchQueryInput = {
type: 'user_search';
@@ -11,7 +11,7 @@ declare module '@/shared/queries' {
interface QueryMap {
user_search: {
input: UserSearchQueryInput;
- output: UserNode[];
+ output: User[];
};
}
}
diff --git a/apps/desktop/src/shared/queries/workspaces/workspace-user-list.ts b/apps/desktop/src/shared/queries/workspaces/workspace-user-list.ts
deleted file mode 100644
index 6189f41b..00000000
--- a/apps/desktop/src/shared/queries/workspaces/workspace-user-list.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { UserNode } from '@colanode/core';
-
-export type WorkspaceUserListQueryInput = {
- type: 'workspace_user_list';
- userId: string;
- page: number;
- count: number;
-};
-
-declare module '@/shared/queries' {
- interface QueryMap {
- workspace_user_list: {
- input: WorkspaceUserListQueryInput;
- output: UserNode[];
- };
- }
-}
diff --git a/apps/desktop/src/shared/types/events.ts b/apps/desktop/src/shared/types/events.ts
index 047b00b4..25d5f322 100644
--- a/apps/desktop/src/shared/types/events.ts
+++ b/apps/desktop/src/shared/types/events.ts
@@ -5,6 +5,25 @@ import { Interaction } from '@/shared/types/interactions';
import { Download, Upload } from '@/shared/types/nodes';
import { Server } from '@/shared/types/servers';
import { Workspace } from '@/shared/types/workspaces';
+import { User } from '@/shared/types/users';
+
+export type UserCreatedEvent = {
+ type: 'user_created';
+ userId: string;
+ user: User;
+};
+
+export type UserUpdatedEvent = {
+ type: 'user_updated';
+ userId: string;
+ user: User;
+};
+
+export type UserDeletedEvent = {
+ type: 'user_deleted';
+ userId: string;
+ user: User;
+};
export type NodeCreatedEvent = {
type: 'node_created';
@@ -153,6 +172,9 @@ export type InteractionUpdatedEvent = {
};
export type Event =
+ | UserCreatedEvent
+ | UserUpdatedEvent
+ | UserDeletedEvent
| NodeCreatedEvent
| NodeUpdatedEvent
| NodeDeletedEvent
diff --git a/apps/desktop/src/shared/types/interactions.ts b/apps/desktop/src/shared/types/interactions.ts
index 14afc68a..e737923a 100644
--- a/apps/desktop/src/shared/types/interactions.ts
+++ b/apps/desktop/src/shared/types/interactions.ts
@@ -1,9 +1,8 @@
-import { InteractionAttributes, NodeType } from '@colanode/core';
+import { InteractionAttributes } from '@colanode/core';
export type Interaction = {
userId: string;
nodeId: string;
- nodeType: NodeType;
attributes: InteractionAttributes;
createdAt: Date;
updatedAt: Date | null;
diff --git a/apps/desktop/src/shared/types/nodes.ts b/apps/desktop/src/shared/types/nodes.ts
index 23b3e046..966ad721 100644
--- a/apps/desktop/src/shared/types/nodes.ts
+++ b/apps/desktop/src/shared/types/nodes.ts
@@ -6,18 +6,6 @@ export type NodeCollaborator = {
role: NodeRole;
};
-export type UserNode = {
- userId: string;
- nodeId: string;
- lastSeenAt: string | null;
- lastSeenVersionId: string | null;
- mentionsCount: number;
- attributes: string | null;
- versionId: string;
- createdAt: string;
- updatedAt: string | null;
-};
-
export type Download = {
nodeId: string;
uploadId: string;
diff --git a/apps/desktop/src/shared/types/users.ts b/apps/desktop/src/shared/types/users.ts
new file mode 100644
index 00000000..c1a2a29c
--- /dev/null
+++ b/apps/desktop/src/shared/types/users.ts
@@ -0,0 +1,13 @@
+import { WorkspaceRole } from '@colanode/core';
+
+export type User = {
+ id: string;
+ email: string;
+ name: string;
+ avatar: string | null;
+ customName: string | null;
+ customAvatar: string | null;
+ role: WorkspaceRole;
+ createdAt: string;
+ updatedAt: string | null;
+};
diff --git a/apps/server/src/controllers/client/accounts/account-sync.ts b/apps/server/src/controllers/client/accounts/account-sync.ts
index 6b817383..3c1607b7 100644
--- a/apps/server/src/controllers/client/accounts/account-sync.ts
+++ b/apps/server/src/controllers/client/accounts/account-sync.ts
@@ -27,24 +27,22 @@ export const accountSyncHandler = async (
}
const workspaceOutputs: WorkspaceOutput[] = [];
- const workspaceUsers = await database
- .selectFrom('workspace_users')
+ const users = await database
+ .selectFrom('users')
.where('account_id', '=', account.id)
.selectAll()
.execute();
- if (workspaceUsers.length > 0) {
- const workspaceIds = workspaceUsers.map((wu) => wu.workspace_id);
+ if (users.length > 0) {
+ const workspaceIds = users.map((u) => u.workspace_id);
const workspaces = await database
.selectFrom('workspaces')
.where('id', 'in', workspaceIds)
.selectAll()
.execute();
- for (const workspaceUser of workspaceUsers) {
- const workspace = workspaces.find(
- (w) => w.id === workspaceUser.workspace_id
- );
+ for (const user of users) {
+ const workspace = workspaces.find((w) => w.id === user.workspace_id);
if (!workspace) {
continue;
@@ -53,13 +51,13 @@ export const accountSyncHandler = async (
workspaceOutputs.push({
id: workspace.id,
name: workspace.name,
- versionId: workspaceUser.version_id,
+ versionId: workspace.version_id,
avatar: workspace.avatar,
description: workspace.description,
user: {
- id: workspaceUser.id,
- accountId: workspaceUser.account_id,
- role: workspaceUser.role as WorkspaceRole,
+ id: user.id,
+ accountId: user.account_id,
+ role: user.role as WorkspaceRole,
},
});
}
diff --git a/apps/server/src/controllers/client/accounts/account-update.ts b/apps/server/src/controllers/client/accounts/account-update.ts
index b6d1f66b..c842e7ca 100644
--- a/apps/server/src/controllers/client/accounts/account-update.ts
+++ b/apps/server/src/controllers/client/accounts/account-update.ts
@@ -3,7 +3,6 @@ import { AccountUpdateInput, AccountUpdateOutput } from '@colanode/core';
import { database } from '@/data/database';
import { ApiError } from '@/types/api';
-import { nodeService } from '@/services/node-service';
import { eventBus } from '@/lib/event-bus';
export const accountUpdateHandler = async (
@@ -57,46 +56,33 @@ export const accountUpdateHandler = async (
.execute();
const users = await database
- .selectFrom('nodes')
- .selectAll()
- .where(
- 'id',
- 'in',
- database
- .selectFrom('workspace_users')
- .select('id')
- .where('account_id', '=', account.id)
- )
+ .selectFrom('users')
+ .select(['id', 'workspace_id'])
+ .where('account_id', '=', account.id)
.execute();
- for (const user of users) {
- if (user.attributes.type !== 'user') {
- throw new Error('User node not found.');
- }
-
- const name = user.attributes.name ?? null;
- const avatar = user.attributes.avatar ?? null;
-
- if (account.name !== name || account.avatar !== avatar) {
- continue;
+ if (users.length > 0) {
+ const userIds = users.map((u) => u.id);
+
+ await database
+ .updateTable('users')
+ .set({
+ name: input.name,
+ avatar: input.avatar,
+ updated_at: new Date(),
+ updated_by: account.id,
+ })
+ .where('id', 'in', userIds)
+ .execute();
+
+ for (const user of users) {
+ eventBus.publish({
+ type: 'user_updated',
+ userId: user.id,
+ accountId: account.id,
+ workspaceId: user.workspace_id,
+ });
}
-
- await nodeService.updateNode({
- nodeId: user.id,
- userId: user.created_by,
- workspaceId: user.workspace_id,
- updater: (attributes) => {
- if (attributes.type !== 'user') {
- return null;
- }
-
- return {
- ...attributes,
- name: input.name,
- avatar: input.avatar,
- };
- },
- });
}
eventBus.publish({
diff --git a/apps/server/src/controllers/client/workspaces/files/file-download-get.ts b/apps/server/src/controllers/client/workspaces/files/file-download-get.ts
index f1a75e09..c7d14521 100644
--- a/apps/server/src/controllers/client/workspaces/files/file-download-get.ts
+++ b/apps/server/src/controllers/client/workspaces/files/file-download-get.ts
@@ -14,7 +14,7 @@ export const fileDownloadGetHandler = async (
): Promise<void> => {
const fileId = req.params.fileId as string;
- const role = await fetchNodeRole(fileId, res.locals.workspaceUser.id);
+ const role = await fetchNodeRole(fileId, res.locals.user.id);
if (role === null || !hasCollaboratorAccess(role)) {
res.status(403).json({
code: ApiError.Forbidden,
diff --git a/apps/server/src/controllers/client/workspaces/files/file-upload-complete.ts b/apps/server/src/controllers/client/workspaces/files/file-upload-complete.ts
index 40272ea0..e21a0d63 100644
--- a/apps/server/src/controllers/client/workspaces/files/file-upload-complete.ts
+++ b/apps/server/src/controllers/client/workspaces/files/file-upload-complete.ts
@@ -100,7 +100,7 @@ export const fileUploadCompleteHandler = async (
mime_type: metadata.mimeType,
size: metadata.size,
type: extractFileType(metadata.mimeType),
- created_by: res.locals.workspaceUser.id,
+ created_by: res.locals.user.id,
created_at: new Date(metadata.createdAt),
completed_at: new Date(),
})
@@ -108,7 +108,7 @@ export const fileUploadCompleteHandler = async (
await nodeService.updateNode({
nodeId: file.id,
- userId: res.locals.workspaceUser.id,
+ userId: res.locals.user.id,
workspaceId: workspaceId,
updater: (attributes) => ({
...attributes,
diff --git a/apps/server/src/controllers/client/workspaces/files/file-upload-init.ts b/apps/server/src/controllers/client/workspaces/files/file-upload-init.ts
index ba59ae32..a6616149 100644
--- a/apps/server/src/controllers/client/workspaces/files/file-upload-init.ts
+++ b/apps/server/src/controllers/client/workspaces/files/file-upload-init.ts
@@ -41,7 +41,7 @@ export const fileUploadInitHandler = async (
return;
}
- if (node.created_by !== res.locals.workspaceUser.id) {
+ if (node.created_by !== res.locals.user.id) {
res.status(403).json({
code: ApiError.Forbidden,
message: 'Forbidden.',
diff --git a/apps/server/src/controllers/client/workspaces/transactions/transactions-get.ts b/apps/server/src/controllers/client/workspaces/transactions/transactions-get.ts
index ad708663..197a3fc9 100644
--- a/apps/server/src/controllers/client/workspaces/transactions/transactions-get.ts
+++ b/apps/server/src/controllers/client/workspaces/transactions/transactions-get.ts
@@ -11,7 +11,7 @@ export const transactionsGetHandler = async (
): Promise<void> => {
const nodeId = req.params.nodeId as string;
- const role = await fetchNodeRole(nodeId, res.locals.workspaceUser.id);
+ const role = await fetchNodeRole(nodeId, res.locals.user.id);
if (role === null || !hasViewerAccess(role)) {
res.status(403).json({
code: ApiError.Forbidden,
diff --git a/apps/server/src/controllers/client/workspaces/transactions/transactions-sync.ts b/apps/server/src/controllers/client/workspaces/transactions/transactions-sync.ts
index 44d5cae0..1b4c72e2 100644
--- a/apps/server/src/controllers/client/workspaces/transactions/transactions-sync.ts
+++ b/apps/server/src/controllers/client/workspaces/transactions/transactions-sync.ts
@@ -9,7 +9,7 @@ import {
SyncTransactionStatus,
} from '@colanode/core';
-import { SelectWorkspaceUser } from '@/data/schema';
+import { SelectUser } from '@/data/schema';
import { nodeService } from '@/services/node-service';
export const transactionsSyncHandler = async (
@@ -21,10 +21,7 @@ export const transactionsSyncHandler = async (
const results: SyncTransactionResult[] = [];
for (const transaction of input.transactions) {
try {
- const status = await handleLocalTransaction(
- res.locals.workspaceUser,
- transaction
- );
+ const status = await handleLocalTransaction(res.locals.user, transaction);
results.push({
id: transaction.id,
status: status,
@@ -43,25 +40,25 @@ export const transactionsSyncHandler = async (
};
const handleLocalTransaction = async (
- workspaceUser: SelectWorkspaceUser,
+ user: SelectUser,
transaction: LocalTransaction
): Promise<SyncTransactionStatus> => {
if (transaction.operation === 'create') {
- return await handleCreateTransaction(workspaceUser, transaction);
+ return await handleCreateTransaction(user, transaction);
} else if (transaction.operation === 'update') {
- return await handleUpdateTransaction(workspaceUser, transaction);
+ return await handleUpdateTransaction(user, transaction);
} else if (transaction.operation === 'delete') {
- return await handleDeleteTransaction(workspaceUser, transaction);
+ return await handleDeleteTransaction(user, transaction);
} else {
return 'error';
}
};
const handleCreateTransaction = async (
- workspaceUser: SelectWorkspaceUser,
+ user: SelectUser,
transaction: LocalCreateTransaction
): Promise<SyncTransactionStatus> => {
- const output = await nodeService.applyCreateTransaction(workspaceUser, {
+ const output = await nodeService.applyCreateTransaction(user, {
id: transaction.id,
nodeId: transaction.nodeId,
data: transaction.data,
@@ -76,10 +73,10 @@ const handleCreateTransaction = async (
};
const handleUpdateTransaction = async (
- workspaceUser: SelectWorkspaceUser,
+ user: SelectUser,
transaction: LocalUpdateTransaction
): Promise<SyncTransactionStatus> => {
- const output = await nodeService.applyUpdateTransaction(workspaceUser, {
+ const output = await nodeService.applyUpdateTransaction(user, {
id: transaction.id,
nodeId: transaction.nodeId,
userId: transaction.createdBy,
@@ -95,10 +92,10 @@ const handleUpdateTransaction = async (
};
const handleDeleteTransaction = async (
- workspaceUser: SelectWorkspaceUser,
+ user: SelectUser,
transaction: LocalDeleteTransaction
): Promise<SyncTransactionStatus> => {
- const output = await nodeService.applyDeleteTransaction(workspaceUser, {
+ const output = await nodeService.applyDeleteTransaction(user, {
id: transaction.id,
nodeId: transaction.nodeId,
createdAt: new Date(transaction.createdAt),
diff --git a/apps/server/src/controllers/client/workspaces/users/user-create.ts b/apps/server/src/controllers/client/workspaces/users/user-create.ts
index 50461f73..84bc759b 100644
--- a/apps/server/src/controllers/client/workspaces/users/user-create.ts
+++ b/apps/server/src/controllers/client/workspaces/users/user-create.ts
@@ -3,25 +3,25 @@ import {
AccountStatus,
generateId,
IdType,
- WorkspaceUserInviteResult,
- WorkspaceUsersInviteInput,
- WorkspaceUserStatus,
+ UserInviteResult,
+ UsersInviteInput,
+ UserStatus,
} from '@colanode/core';
import { database } from '@/data/database';
import { ApiError } from '@/types/api';
-import { fetchNode, mapNode } from '@/lib/nodes';
+import { fetchNode } from '@/lib/nodes';
import { getNameFromEmail } from '@/lib/utils';
-import { nodeService } from '@/services/node-service';
-import { SelectWorkspaceUser } from '@/data/schema';
+import { SelectUser } from '@/data/schema';
+import { eventBus } from '@/lib/event-bus';
export const userCreateHandler = async (
req: Request,
res: Response
): Promise<void> => {
const workspaceId = req.params.workspaceId as string;
- const input: WorkspaceUsersInviteInput = req.body;
- const workspaceUser: SelectWorkspaceUser = res.locals.workspaceUser;
+ const input: UsersInviteInput = req.body;
+ const user: SelectUser = res.locals.user;
if (!input.emails || input.emails.length === 0) {
res.status(400).json({
@@ -39,7 +39,7 @@ export const userCreateHandler = async (
return;
}
- if (workspaceUser.role !== 'owner' && workspaceUser.role !== 'admin') {
+ if (user.role !== 'owner' && user.role !== 'admin') {
res.status(403).json({
code: ApiError.Forbidden,
message: 'Forbidden.',
@@ -56,8 +56,7 @@ export const userCreateHandler = async (
return;
}
- const workspaceNode = mapNode(workspaceNodeRow);
- const results: WorkspaceUserInviteResult[] = [];
+ const results: UserInviteResult[] = [];
for (const email of input.emails) {
let account = await database
.selectFrom('accounts')
@@ -91,14 +90,14 @@ export const userCreateHandler = async (
continue;
}
- const existingWorkspaceUser = await database
- .selectFrom('workspace_users')
+ const existingUser = await database
+ .selectFrom('users')
.selectAll()
.where('account_id', '=', account.id)
.where('workspace_id', '=', workspaceId)
.executeTakeFirst();
- if (existingWorkspaceUser) {
+ if (existingUser) {
results.push({
email: email,
result: 'exists',
@@ -107,41 +106,35 @@ export const userCreateHandler = async (
}
const userId = generateId(IdType.User);
- const newWorkspaceUser = await database
- .insertInto('workspace_users')
+ const newUser = await database
+ .insertInto('users')
.returningAll()
.values({
id: userId,
account_id: account.id,
workspace_id: workspaceId,
role: input.role,
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
created_at: new Date(),
created_by: res.locals.account.id,
- status: WorkspaceUserStatus.Active,
- version_id: generateId(IdType.Version),
+ status: UserStatus.Active,
})
.executeTakeFirst();
- if (!newWorkspaceUser) {
+ if (!newUser) {
results.push({
email: email,
result: 'error',
});
}
- await nodeService.createNode({
- nodeId: userId,
- attributes: {
- type: 'user',
- name: account.name,
- email: account.email,
- role: input.role,
- accountId: account.id,
- parentId: workspaceId,
- },
- userId: workspaceUser.id,
+ eventBus.publish({
+ type: 'user_created',
+ accountId: account.id,
+ userId: userId,
workspaceId: workspaceId,
- ancestors: [workspaceNode],
});
results.push({
diff --git a/apps/server/src/controllers/client/workspaces/users/user-role-update.ts b/apps/server/src/controllers/client/workspaces/users/user-role-update.ts
index 7f9cfc37..a08f997d 100644
--- a/apps/server/src/controllers/client/workspaces/users/user-role-update.ts
+++ b/apps/server/src/controllers/client/workspaces/users/user-role-update.ts
@@ -1,26 +1,20 @@
import { Request, Response } from 'express';
-import {
- generateId,
- IdType,
- WorkspaceUserRoleUpdateInput,
-} from '@colanode/core';
+import { UserRoleUpdateInput } from '@colanode/core';
import { database } from '@/data/database';
import { ApiError } from '@/types/api';
-import { nodeService } from '@/services/node-service';
-import { mapTransaction } from '@/lib/nodes';
-import { SelectWorkspaceUser } from '@/data/schema';
+import { SelectUser } from '@/data/schema';
+import { eventBus } from '@/lib/event-bus';
export const userRoleUpdateHandler = async (
req: Request,
res: Response
): Promise<void> => {
- const workspaceId = req.params.workspaceId as string;
const userId = req.params.userId as string;
- const input: WorkspaceUserRoleUpdateInput = req.body;
- const workspaceUser: SelectWorkspaceUser = res.locals.workspaceUser;
+ const input: UserRoleUpdateInput = req.body;
+ const user: SelectUser = res.locals.user;
- if (workspaceUser.role !== 'owner' && workspaceUser.role !== 'admin') {
+ if (user.role !== 'owner' && user.role !== 'admin') {
res.status(403).json({
code: ApiError.Forbidden,
message: 'Forbidden.',
@@ -28,27 +22,13 @@ export const userRoleUpdateHandler = async (
return;
}
- const workspaceUserToUpdate = await database
- .selectFrom('workspace_users')
+ const userToUpdate = await database
+ .selectFrom('users')
.selectAll()
.where('id', '=', userId)
.executeTakeFirst();
- if (!workspaceUserToUpdate) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'NotFound.',
- });
- return;
- }
-
- const user = await database
- .selectFrom('nodes')
- .selectAll()
- .where('id', '=', workspaceUserToUpdate.id)
- .executeTakeFirst();
-
- if (!user) {
+ if (!userToUpdate) {
res.status(404).json({
code: ApiError.ResourceNotFound,
message: 'NotFound.',
@@ -57,39 +37,23 @@ export const userRoleUpdateHandler = async (
}
await database
- .updateTable('workspace_users')
+ .updateTable('users')
.set({
role: input.role,
updated_at: new Date(),
- updated_by: workspaceUser.account_id,
- version_id: generateId(IdType.Version),
+ updated_by: user.id,
})
- .where('id', '=', userId)
+ .where('id', '=', userToUpdate.id)
.execute();
- const updateUserOutput = await nodeService.updateNode({
- nodeId: user.id,
- userId: workspaceUser.account_id,
- workspaceId: workspaceId,
- updater: (attributes) => {
- if (attributes.type !== 'user') {
- return null;
- }
-
- attributes.role = input.role;
- return attributes;
- },
+ eventBus.publish({
+ type: 'user_updated',
+ userId: userToUpdate.id,
+ accountId: user.account_id,
+ workspaceId: userToUpdate.workspace_id,
});
- if (!updateUserOutput) {
- res.status(500).json({
- code: ApiError.InternalServerError,
- message: 'Something went wrong.',
- });
- return;
- }
-
res.status(200).json({
- transaction: mapTransaction(updateUserOutput.transaction),
+ success: true,
});
};
diff --git a/apps/server/src/controllers/client/workspaces/workspace-delete.ts b/apps/server/src/controllers/client/workspaces/workspace-delete.ts
index 745bfc04..d790a2d0 100644
--- a/apps/server/src/controllers/client/workspaces/workspace-delete.ts
+++ b/apps/server/src/controllers/client/workspaces/workspace-delete.ts
@@ -10,7 +10,7 @@ export const workspaceDeleteHandler = async (
): Promise<void> => {
const workspaceId = req.params.workspaceId as string;
- if (res.locals.workspaceUser.role !== 'owner') {
+ if (res.locals.user.role !== 'owner') {
res.status(403).json({
code: ApiError.Forbidden,
message: 'Forbidden.',
diff --git a/apps/server/src/controllers/client/workspaces/workspace-get.ts b/apps/server/src/controllers/client/workspaces/workspace-get.ts
index 16ab869a..9246c4b1 100644
--- a/apps/server/src/controllers/client/workspaces/workspace-get.ts
+++ b/apps/server/src/controllers/client/workspaces/workspace-get.ts
@@ -24,14 +24,14 @@ export const workspaceGetHandler = async (
return;
}
- const workspaceUser = await database
- .selectFrom('workspace_users')
+ const user = await database
+ .selectFrom('users')
.selectAll()
.where('workspace_id', '=', workspaceId)
.where('account_id', '=', res.locals.account.id)
.executeTakeFirst();
- if (!workspaceUser) {
+ if (!user) {
res.status(403).json({
code: ApiError.Forbidden,
message: 'Forbidden.',
@@ -46,9 +46,9 @@ export const workspaceGetHandler = async (
avatar: workspace.avatar,
versionId: workspace.version_id,
user: {
- id: workspaceUser.id,
- accountId: workspaceUser.account_id,
- role: workspaceUser.role as WorkspaceRole,
+ id: user.id,
+ accountId: user.account_id,
+ role: user.role as WorkspaceRole,
},
};
diff --git a/apps/server/src/controllers/client/workspaces/workspace-update.ts b/apps/server/src/controllers/client/workspaces/workspace-update.ts
index 86e4af2b..60359f0c 100644
--- a/apps/server/src/controllers/client/workspaces/workspace-update.ts
+++ b/apps/server/src/controllers/client/workspaces/workspace-update.ts
@@ -2,7 +2,6 @@ import { Request, Response } from 'express';
import { WorkspaceOutput, WorkspaceUpdateInput } from '@colanode/core';
import { database } from '@/data/database';
-import { nodeService } from '@/services/node-service';
import { ApiError } from '@/types/api';
import { eventBus } from '@/lib/event-bus';
@@ -13,7 +12,7 @@ export const workspaceUpdateHandler = async (
const workspaceId = req.params.workspaceId as string;
const input: WorkspaceUpdateInput = req.body;
- if (res.locals.workspaceUser.role !== 'owner') {
+ if (res.locals.user.role !== 'owner') {
res.status(403).json({
code: ApiError.Forbidden,
message: 'Forbidden.',
@@ -42,23 +41,6 @@ export const workspaceUpdateHandler = async (
return;
}
- await nodeService.updateNode({
- nodeId: updatedWorkspace.id,
- userId: res.locals.account.id,
- workspaceId: workspaceId,
- updater: (attributes) => {
- if (attributes.type !== 'workspace') {
- return null;
- }
-
- attributes.name = input.name;
- attributes.description = input.description;
- attributes.avatar = input.avatar;
-
- return attributes;
- },
- });
-
eventBus.publish({
type: 'workspace_updated',
workspaceId: updatedWorkspace.id,
@@ -71,9 +53,9 @@ export const workspaceUpdateHandler = async (
avatar: updatedWorkspace.avatar,
versionId: updatedWorkspace.version_id,
user: {
- id: res.locals.workspaceUser.id,
- accountId: res.locals.workspaceUser.account_id,
- role: res.locals.workspaceUser.role,
+ id: res.locals.user.id,
+ accountId: res.locals.user.account_id,
+ role: res.locals.user.role,
},
};
diff --git a/apps/server/src/data/migrations.ts b/apps/server/src/data/migrations.ts
index d8172f90..369c76d7 100644
--- a/apps/server/src/data/migrations.ts
+++ b/apps/server/src/data/migrations.ts
@@ -68,21 +68,36 @@ const createWorkspacesTable: Migration = {
},
};
-const createWorkspaceUsersTable: Migration = {
+const createUsersTable: Migration = {
up: async (db) => {
+ await sql`
+ CREATE SEQUENCE IF NOT EXISTS users_version_sequence
+ START WITH 1000000000
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `.execute(db);
+
await db.schema
- .createTable('workspace_users')
+ .createTable('users')
.addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
.addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
.addColumn('account_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('email', 'varchar(256)', (col) => col.notNull())
+ .addColumn('name', 'varchar(256)', (col) => col.notNull())
+ .addColumn('avatar', 'varchar(256)')
+ .addColumn('custom_name', 'varchar(256)')
+ .addColumn('custom_avatar', 'varchar(256)')
.addColumn('role', 'varchar(30)', (col) => col.notNull())
- .addColumn('attrs', 'jsonb')
.addColumn('created_at', 'timestamptz', (col) => col.notNull())
.addColumn('created_by', 'varchar(30)', (col) => col.notNull())
.addColumn('updated_at', 'timestamptz')
.addColumn('updated_by', 'varchar(30)')
.addColumn('status', 'integer', (col) => col.notNull())
- .addColumn('version_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('version', 'bigint', (col) =>
+ col.notNull().defaultTo(sql`nextval('users_version_sequence')`)
+ )
.addUniqueConstraint('unique_workspace_account_combination', [
'workspace_id',
'account_id',
@@ -90,7 +105,8 @@ const createWorkspaceUsersTable: Migration = {
.execute();
},
down: async (db) => {
- await db.schema.dropTable('workspace_users').execute();
+ await db.schema.dropTable('users').execute();
+ await sql`DROP SEQUENCE IF EXISTS users_version_sequence`.execute(db);
},
};
@@ -125,7 +141,7 @@ const createNodesTable: Migration = {
const createTransactionsTable: Migration = {
up: async (db) => {
await sql`
- CREATE SEQUENCE IF NOT EXISTS transactions_version_seq
+ CREATE SEQUENCE IF NOT EXISTS transactions_version_sequence
START WITH 1000000000
INCREMENT BY 1
NO MINVALUE
@@ -137,7 +153,6 @@ const createTransactionsTable: Migration = {
.createTable('transactions')
.addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
.addColumn('node_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('node_type', 'varchar(30)', (col) => col.notNull())
.addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
.addColumn('operation', 'varchar(30)', (col) => col.notNull())
.addColumn('data', 'bytea')
@@ -145,13 +160,15 @@ const createTransactionsTable: Migration = {
.addColumn('created_by', 'varchar(30)', (col) => col.notNull())
.addColumn('server_created_at', 'timestamptz', (col) => col.notNull())
.addColumn('version', 'bigint', (col) =>
- col.notNull().defaultTo(sql`nextval('transactions_version_seq')`)
+ col.notNull().defaultTo(sql`nextval('transactions_version_sequence')`)
)
.execute();
},
down: async (db) => {
await db.schema.dropTable('transactions').execute();
- await sql`DROP SEQUENCE IF EXISTS transactions_version_seq`.execute(db);
+ await sql`DROP SEQUENCE IF EXISTS transactions_version_sequence`.execute(
+ db
+ );
},
};
@@ -375,7 +392,6 @@ const createInteractionsTable: Migration = {
.createTable('interactions')
.addColumn('user_id', 'varchar(30)', (col) => col.notNull())
.addColumn('node_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('node_type', 'varchar(30)', (col) => col.notNull())
.addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
.addColumn('attributes', 'jsonb')
.addColumn('created_at', 'timestamptz', (col) => col.notNull())
@@ -417,7 +433,7 @@ export const databaseMigrations: Record<string, Migration> = {
'00001_create_accounts_table': createAccountsTable,
'00002_create_devices_table': createDevicesTable,
'00003_create_workspaces_table': createWorkspacesTable,
- '00004_create_workspace_users_table': createWorkspaceUsersTable,
+ '00004_create_users_table': createUsersTable,
'00005_create_nodes_table': createNodesTable,
'00006_create_transactions_table': createTransactionsTable,
'00007_create_node_paths_table': createNodePathsTable,
diff --git a/apps/server/src/data/schema.ts b/apps/server/src/data/schema.ts
index ff26ef41..ac0a4b67 100644
--- a/apps/server/src/data/schema.ts
+++ b/apps/server/src/data/schema.ts
@@ -69,23 +69,27 @@ export type SelectWorkspace = Selectable<WorkspaceTable>;
export type CreateWorkspace = Insertable<WorkspaceTable>;
export type UpdateWorkspace = Updateable<WorkspaceTable>;
-interface WorkspaceUserTable {
+interface UserTable {
id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
account_id: ColumnType<string, string, never>;
+ email: ColumnType<string, string, string>;
role: ColumnType<WorkspaceRole, WorkspaceRole, WorkspaceRole>;
- attrs: ColumnType<string | null, string | null, string | null>;
+ name: ColumnType<string, string, string>;
+ avatar: ColumnType<string | null, string | null, string | null>;
+ custom_name: ColumnType<string | null, string | null, string | null>;
+ custom_avatar: ColumnType<string | null, string | null, string | null>;
created_at: ColumnType<Date, Date, never>;
created_by: ColumnType<string, string, never>;
updated_at: ColumnType<Date | null, Date | null, Date>;
updated_by: ColumnType<string | null, string | null, string>;
status: ColumnType<number, number, number>;
- version_id: ColumnType<string, string, string>;
+ version: ColumnType<bigint, never, never>;
}
-export type SelectWorkspaceUser = Selectable<WorkspaceUserTable>;
-export type CreateWorkspaceUser = Insertable<WorkspaceUserTable>;
-export type UpdateWorkspaceUser = Updateable<WorkspaceUserTable>;
+export type SelectUser = Selectable<UserTable>;
+export type CreateUser = Insertable<UserTable>;
+export type UpdateUser = Updateable<UserTable>;
interface NodeTable {
id: ColumnType<string, string, never>;
@@ -107,7 +111,6 @@ export type UpdateNode = Updateable<NodeTable>;
interface TransactionTable {
id: ColumnType<string, string, never>;
node_id: ColumnType<string, string, never>;
- node_type: ColumnType<NodeType, NodeType, never>;
workspace_id: ColumnType<string, string, never>;
operation: ColumnType<string, string, never>;
data: ColumnType<Uint8Array | null, Uint8Array | null, Uint8Array | null>;
@@ -178,7 +181,6 @@ export type UpdateUpload = Updateable<UploadTable>;
interface InteractionTable {
user_id: ColumnType<string, string, never>;
node_id: ColumnType<string, string, never>;
- node_type: ColumnType<NodeType, NodeType, never>;
workspace_id: ColumnType<string, string, never>;
attributes: JSONColumnType<
InteractionAttributes,
@@ -200,7 +202,7 @@ export interface DatabaseSchema {
accounts: AccountTable;
devices: DeviceTable;
workspaces: WorkspaceTable;
- workspace_users: WorkspaceUserTable;
+ users: UserTable;
nodes: NodeTable;
transactions: TransactionTable;
collaborations: CollaborationTable;
diff --git a/apps/server/src/lib/nodes.ts b/apps/server/src/lib/nodes.ts
index f6ff243c..0d105141 100644
--- a/apps/server/src/lib/nodes.ts
+++ b/apps/server/src/lib/nodes.ts
@@ -9,6 +9,7 @@ import {
ServerDeletedCollaboration,
ServerInteraction,
ServerTransaction,
+ ServerUser,
} from '@colanode/core';
import { encodeState } from '@colanode/crdt';
@@ -19,6 +20,7 @@ import {
SelectInteraction,
SelectNode,
SelectTransaction,
+ SelectUser,
} from '@/data/schema';
import { NodeCollaborator } from '@/types/nodes';
@@ -60,7 +62,6 @@ export const mapTransaction = (
id: transaction.id,
operation: 'create',
nodeId: transaction.node_id,
- nodeType: transaction.node_type,
workspaceId: transaction.workspace_id,
data: encodeState(transaction.data),
createdAt: transaction.created_at.toISOString(),
@@ -75,7 +76,6 @@ export const mapTransaction = (
id: transaction.id,
operation: 'update',
nodeId: transaction.node_id,
- nodeType: transaction.node_type,
workspaceId: transaction.workspace_id,
data: encodeState(transaction.data),
createdAt: transaction.created_at.toISOString(),
@@ -90,7 +90,6 @@ export const mapTransaction = (
id: transaction.id,
operation: 'delete',
nodeId: transaction.node_id,
- nodeType: transaction.node_type,
workspaceId: transaction.workspace_id,
createdAt: transaction.created_at.toISOString(),
createdBy: transaction.created_by,
@@ -134,7 +133,6 @@ export const mapInteraction = (
return {
userId: interaction.user_id,
nodeId: interaction.node_id,
- nodeType: interaction.node_type,
workspaceId: interaction.workspace_id,
attributes: interaction.attributes,
createdAt: interaction.created_at.toISOString(),
@@ -145,6 +143,22 @@ export const mapInteraction = (
};
};
+export const mapUser = (user: SelectUser): ServerUser => {
+ return {
+ id: user.id,
+ workspaceId: user.workspace_id,
+ email: user.email,
+ role: user.role,
+ name: user.name,
+ avatar: user.avatar,
+ customName: user.custom_name,
+ customAvatar: user.custom_avatar,
+ createdAt: user.created_at.toISOString(),
+ updatedAt: user.updated_at?.toISOString() ?? null,
+ version: user.version.toString(),
+ };
+};
+
export const fetchNode = async (nodeId: string): Promise<SelectNode | null> => {
const result = await database
.selectFrom('nodes')
@@ -215,15 +229,3 @@ export const fetchNodeRole = async (
return extractNodeRole(ancestors.map(mapNode), collaboratorId);
};
-
-export const fetchWorkspaceUsers = async (
- workspaceId: string
-): Promise<string[]> => {
- const result = await database
- .selectFrom('workspace_users')
- .select('id')
- .where('workspace_id', '=', workspaceId)
- .execute();
-
- return result.map((row) => row.id);
-};
diff --git a/apps/server/src/middlewares/workspace.ts b/apps/server/src/middlewares/workspace.ts
index 25a87053..a44e5e11 100644
--- a/apps/server/src/middlewares/workspace.ts
+++ b/apps/server/src/middlewares/workspace.ts
@@ -10,14 +10,14 @@ export const workspaceMiddleware: RequestHandler = async (
) => {
const workspaceId = req.params.workspaceId as string;
- const workspaceUser = await database
- .selectFrom('workspace_users')
+ const user = await database
+ .selectFrom('users')
.selectAll()
.where('workspace_id', '=', workspaceId)
.where('account_id', '=', res.locals.account.id)
.executeTakeFirst();
- if (!workspaceUser) {
+ if (!user) {
res.status(403).json({
code: ApiError.Forbidden,
message: 'Forbidden.',
@@ -25,7 +25,7 @@ export const workspaceMiddleware: RequestHandler = async (
return;
}
- res.locals.workspaceUser = workspaceUser;
+ res.locals.user = user;
next();
};
diff --git a/apps/server/src/services/account-service.ts b/apps/server/src/services/account-service.ts
index 1f97f321..684a3991 100644
--- a/apps/server/src/services/account-service.ts
+++ b/apps/server/src/services/account-service.ts
@@ -13,25 +13,23 @@ import { generateToken } from '@/lib/tokens';
class AccountService {
public async buildLoginOutput(account: SelectAccount): Promise<LoginOutput> {
- const workspaceUsers = await database
- .selectFrom('workspace_users')
+ const users = await database
+ .selectFrom('users')
.where('account_id', '=', account.id)
.selectAll()
.execute();
const workspaceOutputs: WorkspaceOutput[] = [];
- if (workspaceUsers.length > 0) {
- const workspaceIds = workspaceUsers.map((wu) => wu.workspace_id);
+ if (users.length > 0) {
+ const workspaceIds = users.map((u) => u.workspace_id);
const workspaces = await database
.selectFrom('workspaces')
.where('id', 'in', workspaceIds)
.selectAll()
.execute();
- for (const workspaceUser of workspaceUsers) {
- const workspace = workspaces.find(
- (w) => w.id === workspaceUser.workspace_id
- );
+ for (const user of users) {
+ const workspace = workspaces.find((w) => w.id === user.workspace_id);
if (!workspace) {
continue;
@@ -40,13 +38,13 @@ class AccountService {
workspaceOutputs.push({
id: workspace.id,
name: workspace.name,
- versionId: workspaceUser.version_id,
+ versionId: workspace.version_id,
avatar: workspace.avatar,
description: workspace.description,
user: {
- id: workspaceUser.id,
- accountId: workspaceUser.account_id,
- role: workspaceUser.role as WorkspaceRole,
+ id: user.id,
+ accountId: user.account_id,
+ role: user.role as WorkspaceRole,
},
});
}
diff --git a/apps/server/src/services/interaction-service.ts b/apps/server/src/services/interaction-service.ts
index a4f17994..2e07347a 100644
--- a/apps/server/src/services/interaction-service.ts
+++ b/apps/server/src/services/interaction-service.ts
@@ -15,21 +15,18 @@ class InteractionService {
accountId: string,
message: SyncInteractionsMessage
) {
- const workspaceUser = await database
- .selectFrom('workspace_users')
+ const user = await database
+ .selectFrom('users')
.selectAll()
.where('id', '=', message.userId)
.executeTakeFirst();
- if (!workspaceUser || workspaceUser.account_id !== accountId) {
+ if (!user || user.account_id !== accountId) {
return false;
}
for (let i = 0; i < UPDATE_RETRIES_COUNT; i++) {
- const synced = await this.trySyncInteraction(
- workspaceUser.workspace_id,
- message
- );
+ const synced = await this.trySyncInteraction(user.workspace_id, message);
if (synced) {
return true;
@@ -92,7 +89,6 @@ class InteractionService {
type: 'interaction_updated',
userId: message.userId,
nodeId: message.nodeId,
- nodeType: message.nodeType,
workspaceId,
});
@@ -106,7 +102,6 @@ class InteractionService {
.values({
user_id: message.userId,
node_id: message.nodeId,
- node_type: message.nodeType,
workspace_id: workspaceId,
attributes: JSON.stringify(attributes),
created_at: new Date(firstEvent.createdAt),
@@ -120,7 +115,6 @@ class InteractionService {
type: 'interaction_updated',
userId: message.userId,
nodeId: message.nodeId,
- nodeType: message.nodeType,
workspaceId,
});
diff --git a/apps/server/src/services/node-service.ts b/apps/server/src/services/node-service.ts
index 412ce0e2..948b3fab 100644
--- a/apps/server/src/services/node-service.ts
+++ b/apps/server/src/services/node-service.ts
@@ -18,7 +18,7 @@ import {
CreateNode,
CreateTransaction,
DatabaseSchema,
- SelectWorkspaceUser,
+ SelectUser,
} from '@/data/schema';
import { eventBus } from '@/lib/event-bus';
import { fetchNodeAncestors, mapNode } from '@/lib/nodes';
@@ -76,7 +76,6 @@ class NodeService {
const createTransaction: CreateTransaction = {
id: transactionId,
node_id: input.nodeId,
- node_type: input.attributes.type,
workspace_id: input.workspaceId,
operation: 'create',
data: update,
@@ -202,7 +201,6 @@ class NodeService {
.values({
id: transactionId,
node_id: input.nodeId,
- node_type: node.type,
workspace_id: input.workspaceId,
operation: 'update',
data: update,
@@ -248,7 +246,7 @@ class NodeService {
}
public async applyCreateTransaction(
- workspaceUser: SelectWorkspaceUser,
+ user: SelectUser,
input: ApplyCreateTransactionInput
): Promise<ApplyCreateTransactionOutput | null> {
const ydoc = new YDoc();
@@ -261,10 +259,10 @@ class NodeService {
const ancestors = ancestorRows.map(mapNode);
const context = new NodeMutationContext(
- workspaceUser.account_id,
- workspaceUser.workspace_id,
- workspaceUser.id,
- workspaceUser.role,
+ user.account_id,
+ user.workspace_id,
+ user.id,
+ user.role,
ancestors
);
@@ -289,7 +287,6 @@ class NodeService {
const createTransaction: CreateTransaction = {
id: input.id,
node_id: input.nodeId,
- node_type: attributes.type,
workspace_id: context.workspaceId,
operation: 'create',
data:
@@ -325,11 +322,11 @@ class NodeService {
}
public async applyUpdateTransaction(
- workspaceUser: SelectWorkspaceUser,
+ user: SelectUser,
input: ApplyUpdateTransactionInput
): Promise<ApplyUpdateTransactionOutput | null> {
for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryApplyUpdateTransaction(workspaceUser, input);
+ const result = await this.tryApplyUpdateTransaction(user, input);
if (result.type === 'success') {
return result.output;
@@ -344,7 +341,7 @@ class NodeService {
}
private async tryApplyUpdateTransaction(
- workspaceUser: SelectWorkspaceUser,
+ user: SelectUser,
input: ApplyUpdateTransactionInput
): Promise<UpdateResult<ApplyUpdateTransactionOutput>> {
const ancestorRows = await fetchNodeAncestors(input.nodeId);
@@ -381,10 +378,10 @@ class NodeService {
}
const context = new NodeMutationContext(
- workspaceUser.account_id,
- workspaceUser.workspace_id,
- workspaceUser.id,
- workspaceUser.role,
+ user.account_id,
+ user.workspace_id,
+ user.id,
+ user.role,
ancestors
);
@@ -425,7 +422,6 @@ class NodeService {
id: input.id,
node_id: input.nodeId,
workspace_id: context.workspaceId,
- node_type: node.type,
operation: 'update',
data:
typeof input.data === 'string'
@@ -501,7 +497,7 @@ class NodeService {
}
public async applyDeleteTransaction(
- workspaceUser: SelectWorkspaceUser,
+ user: SelectUser,
input: ApplyDeleteTransactionInput
): Promise<ApplyDeleteTransactionOutput | null> {
const ancestorRows = await fetchNodeAncestors(input.nodeId);
@@ -513,10 +509,10 @@ class NodeService {
const model = registry.getModel(node.attributes.type);
const context = new NodeMutationContext(
- workspaceUser.account_id,
- workspaceUser.workspace_id,
- workspaceUser.id,
- workspaceUser.role,
+ user.account_id,
+ user.workspace_id,
+ user.id,
+ user.role,
ancestors
);
@@ -548,11 +544,10 @@ class NodeService {
.values({
id: input.id,
node_id: input.nodeId,
- workspace_id: workspaceUser.workspace_id,
- node_type: node.type,
+ workspace_id: user.workspace_id,
operation: 'delete',
created_at: input.createdAt,
- created_by: workspaceUser.id,
+ created_by: user.id,
server_created_at: new Date(),
})
.executeTakeFirst();
@@ -580,13 +575,13 @@ class NodeService {
type: 'node_deleted',
nodeId: input.nodeId,
nodeType: node.type,
- workspaceId: workspaceUser.workspace_id,
+ workspaceId: user.workspace_id,
});
await jobService.addJob({
type: 'clean_node_data',
nodeId: input.nodeId,
- workspaceId: workspaceUser.workspace_id,
+ workspaceId: user.workspace_id,
});
return {
diff --git a/apps/server/src/services/socket-connection.ts b/apps/server/src/services/socket-connection.ts
index f30f2b32..26b2d744 100644
--- a/apps/server/src/services/socket-connection.ts
+++ b/apps/server/src/services/socket-connection.ts
@@ -5,10 +5,10 @@ import {
InteractionsBatchMessage,
Message,
TransactionsBatchMessage,
- NodeType,
SyncConsumerType,
WorkspaceStatus,
DeletedCollaborationsBatchMessage,
+ UsersBatchMessage,
} from '@colanode/core';
import { interactionService } from '@/services/interaction-service';
@@ -20,6 +20,7 @@ import {
mapDeletedCollaboration,
mapInteraction,
mapTransaction,
+ mapUser,
} from '@/lib/nodes';
import {
AccountUpdatedEvent,
@@ -30,13 +31,12 @@ import {
NodeCreatedEvent,
NodeDeletedEvent,
NodeUpdatedEvent,
+ UserCreatedEvent,
+ UserUpdatedEvent,
WorkspaceDeletedEvent,
WorkspaceUpdatedEvent,
- WorkspaceUserCreatedEvent,
} from '@/types/events';
-const PUBLIC_NODES: NodeType[] = ['workspace', 'user'];
-
type SocketSyncConsumer = {
type: SyncConsumerType;
cursor: string;
@@ -99,8 +99,10 @@ export class SocketConnection {
this.handleInteractionUpdatedEvent(event);
} else if (event.type === 'account_updated') {
this.handleAccountUpdatedEvent(event);
- } else if (event.type === 'workspace_user_created') {
- this.handleWorkspaceUserCreatedEvent(event);
+ } else if (event.type === 'user_created') {
+ this.handleUserCreatedEvent(event);
+ } else if (event.type === 'user_updated') {
+ this.handleUserUpdatedEvent(event);
} else if (event.type === 'workspace_updated') {
this.handleWorkspaceUpdatedEvent(event);
} else if (event.type === 'workspace_deleted') {
@@ -155,6 +157,8 @@ export class SocketConnection {
this.consumeCollaborations(user, consumer);
} else if (consumer.type === 'interactions') {
this.consumeInteractions(user, consumer);
+ } else if (consumer.type === 'users') {
+ this.consumeUsers(user, consumer);
}
}
@@ -179,15 +183,7 @@ export class SocketConnection {
.onRef('c.node_id', '=', 't.node_id')
)
.selectAll('t')
- .where((eb) =>
- eb.or([
- eb.and([
- eb('t.workspace_id', '=', user.workspaceId),
- eb('t.node_type', 'in', PUBLIC_NODES),
- ]),
- eb('c.node_id', '=', eb.ref('t.node_id')),
- ])
- )
+ .whereRef('c.node_id', '=', 't.node_id')
.where('t.version', '>', BigInt(consumer.cursor))
.orderBy('t.version', 'asc')
.limit(20)
@@ -316,15 +312,7 @@ export class SocketConnection {
.on('c.user_id', '=', user.userId)
.onRef('c.node_id', '=', 'i.node_id')
)
- .where((eb) =>
- eb.or([
- eb.and([
- eb('i.workspace_id', '=', user.workspaceId),
- eb('i.node_type', 'in', PUBLIC_NODES),
- ]),
- eb('c.node_id', '=', eb.ref('i.node_id')),
- ])
- )
+ .whereRef('c.node_id', '=', 'i.node_id')
.selectAll('i')
.where('i.version', '>', BigInt(consumer.cursor))
.orderBy('i.version', 'asc')
@@ -350,6 +338,41 @@ export class SocketConnection {
this.sendMessage(message);
}
+ private async consumeUsers(user: SocketUser, consumer: SocketSyncConsumer) {
+ if (consumer.fetching) {
+ return;
+ }
+
+ consumer.fetching = true;
+ this.logger.trace(
+ `Checking for pending users for ${this.account.id} and user ${user.userId} with cursor ${consumer.cursor}`
+ );
+
+ const unsyncedUsers = await database
+ .selectFrom('users')
+ .selectAll()
+ .where('workspace_id', '=', user.workspaceId)
+ .where('version', '>', BigInt(consumer.cursor))
+ .orderBy('version', 'asc')
+ .limit(50)
+ .execute();
+
+ if (unsyncedUsers.length === 0) {
+ consumer.fetching = false;
+ return;
+ }
+
+ const users = unsyncedUsers.map(mapUser);
+ const message: UsersBatchMessage = {
+ type: 'users_batch',
+ userId: user.userId,
+ users,
+ };
+
+ user.consumers.delete(consumer.type);
+ this.sendMessage(message);
+ }
+
private async handleNodeCreatedEvent(event: NodeCreatedEvent) {
for (const user of this.users.values()) {
if (user.workspaceId !== event.workspaceId) {
@@ -449,6 +472,32 @@ export class SocketConnection {
}
}
+ private handleUserCreatedEvent(event: UserCreatedEvent) {
+ for (const user of this.users.values()) {
+ if (user.userId !== event.userId) {
+ continue;
+ }
+
+ const usersConsumer = user.consumers.get('users');
+ if (usersConsumer) {
+ this.consumePendingSync(user, usersConsumer);
+ }
+ }
+ }
+
+ private handleUserUpdatedEvent(event: UserUpdatedEvent) {
+ for (const user of this.users.values()) {
+ if (user.userId !== event.userId) {
+ continue;
+ }
+
+ const usersConsumer = user.consumers.get('users');
+ if (usersConsumer) {
+ this.consumePendingSync(user, usersConsumer);
+ }
+ }
+ }
+
private async getOrCreateUser(userId: string): Promise<SocketUser | null> {
const existingUser = this.users.get(userId);
if (existingUser) {
@@ -472,16 +521,16 @@ export class SocketConnection {
}
private async fetchAndCreateUser(userId: string): Promise<SocketUser | null> {
- const workspaceUser = await database
- .selectFrom('workspace_users')
+ const user = await database
+ .selectFrom('users')
.where('id', '=', userId)
.selectAll()
.executeTakeFirst();
if (
- !workspaceUser ||
- workspaceUser.status !== WorkspaceStatus.Active ||
- workspaceUser.account_id !== this.account.id
+ !user ||
+ user.status !== WorkspaceStatus.Active ||
+ user.account_id !== this.account.id
) {
return null;
}
@@ -494,7 +543,7 @@ export class SocketConnection {
// Create and store the new SocketUser
const newSocketUser: SocketUser = {
userId,
- workspaceId: workspaceUser.workspace_id,
+ workspaceId: user.workspace_id,
consumers: new Map(),
};
@@ -513,25 +562,12 @@ export class SocketConnection {
});
}
- private handleWorkspaceUserCreatedEvent(event: WorkspaceUserCreatedEvent) {
- if (event.accountId !== this.account.id) {
- return;
- }
-
- this.sendMessage({
- type: 'workspace_user_created',
- workspaceId: event.workspaceId,
- userId: event.userId,
- accountId: event.accountId,
- });
- }
-
private handleWorkspaceUpdatedEvent(event: WorkspaceUpdatedEvent) {
- const workspaceUsers = Array.from(this.users.values()).filter(
+ const users = Array.from(this.users.values()).filter(
(user) => user.workspaceId === event.workspaceId
);
- if (workspaceUsers.length === 0) {
+ if (users.length === 0) {
return;
}
@@ -542,11 +578,11 @@ export class SocketConnection {
}
private handleWorkspaceDeletedEvent(event: WorkspaceDeletedEvent) {
- const workspaceUsers = Array.from(this.users.values()).filter(
+ const users = Array.from(this.users.values()).filter(
(user) => user.workspaceId === event.workspaceId
);
- if (workspaceUsers.length === 0) {
+ if (users.length === 0) {
return;
}
diff --git a/apps/server/src/services/workspace-service.ts b/apps/server/src/services/workspace-service.ts
index d49933d9..1ab596ea 100644
--- a/apps/server/src/services/workspace-service.ts
+++ b/apps/server/src/services/workspace-service.ts
@@ -4,7 +4,7 @@ import {
WorkspaceCreateInput,
WorkspaceOutput,
WorkspaceStatus,
- WorkspaceUserStatus,
+ UserStatus,
} from '@colanode/core';
import { database } from '@/data/database';
@@ -42,58 +42,27 @@ class WorkspaceService {
throw new Error('Failed to create workspace.');
}
- const workspaceUser = await database
- .insertInto('workspace_users')
+ const user = await database
+ .insertInto('users')
.values({
id: userId,
account_id: account.id,
workspace_id: workspaceId,
role: 'owner',
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
created_at: date,
created_by: account.id,
- status: WorkspaceUserStatus.Active,
- version_id: generateId(IdType.Version),
+ status: UserStatus.Active,
})
.returningAll()
.executeTakeFirst();
- if (!workspaceUser) {
+ if (!user) {
throw new Error('Failed to create workspace user.');
}
- const createWorkspaceNodeOutput = await nodeService.createNode({
- nodeId: workspaceId,
- attributes: {
- type: 'workspace',
- name: input.name,
- description: input.description,
- avatar: input.avatar,
- parentId: workspaceId,
- },
- userId: userId,
- workspaceId: workspaceId,
- ancestors: [],
- });
-
- if (!createWorkspaceNodeOutput) {
- throw new Error('Failed to create workspace node.');
- }
-
- await nodeService.createNode({
- nodeId: userId,
- attributes: {
- type: 'user',
- name: account.name,
- email: account.email,
- role: 'owner',
- accountId: account.id,
- parentId: workspaceId,
- },
- userId: userId,
- workspaceId: workspaceId,
- ancestors: [],
- });
-
const createSpaceNodeOutput = await nodeService.createNode({
nodeId: spaceId,
attributes: {
@@ -144,7 +113,7 @@ class WorkspaceService {
});
eventBus.publish({
- type: 'workspace_user_created',
+ type: 'user_created',
userId: userId,
workspaceId: workspaceId,
accountId: account.id,
@@ -157,9 +126,9 @@ class WorkspaceService {
avatar: workspace.avatar,
versionId: workspace.version_id,
user: {
- id: workspaceUser.id,
- accountId: workspaceUser.account_id,
- role: workspaceUser.role,
+ id: user.id,
+ accountId: user.account_id,
+ role: user.role,
},
};
}
diff --git a/apps/server/src/types/events.ts b/apps/server/src/types/events.ts
index d9ef61ba..d501055b 100644
--- a/apps/server/src/types/events.ts
+++ b/apps/server/src/types/events.ts
@@ -37,12 +37,18 @@ export type InteractionUpdatedEvent = {
type: 'interaction_updated';
userId: string;
nodeId: string;
- nodeType: NodeType;
workspaceId: string;
};
-export type WorkspaceUserCreatedEvent = {
- type: 'workspace_user_created';
+export type UserCreatedEvent = {
+ type: 'user_created';
+ userId: string;
+ workspaceId: string;
+ accountId: string;
+};
+
+export type UserUpdatedEvent = {
+ type: 'user_updated';
userId: string;
workspaceId: string;
accountId: string;
@@ -81,7 +87,8 @@ export type Event =
| CollaboratorAddedEvent
| CollaboratorRemovedEvent
| InteractionUpdatedEvent
- | WorkspaceUserCreatedEvent
+ | UserCreatedEvent
+ | UserUpdatedEvent
| AccountUpdatedEvent
| WorkspaceCreatedEvent
| WorkspaceUpdatedEvent
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5d35c1cb..ab888137 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -17,8 +17,6 @@ export * from './registry/message';
export * from './registry/page';
export * from './registry/record';
export * from './registry/space';
-export * from './registry/user';
-export * from './registry/workspace';
export * from './registry/zod';
export * from './types/accounts';
export * from './types/files';
diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.ts
index 12e90ff5..9a96d88a 100644
--- a/packages/core/src/registry/index.ts
+++ b/packages/core/src/registry/index.ts
@@ -8,8 +8,6 @@ import { MessageAttributes, messageModel } from './message';
import { PageAttributes, pageModel } from './page';
import { RecordAttributes, recordModel } from './record';
import { SpaceAttributes, spaceModel } from './space';
-import { UserAttributes, userModel } from './user';
-import { WorkspaceAttributes, workspaceModel } from './workspace';
type NodeBase = {
id: string;
@@ -75,16 +73,6 @@ export type SpaceNode = NodeBase & {
attributes: SpaceAttributes;
};
-export type UserNode = NodeBase & {
- type: 'user';
- attributes: UserAttributes;
-};
-
-export type WorkspaceNode = NodeBase & {
- type: 'workspace';
- attributes: WorkspaceAttributes;
-};
-
export type NodeType =
| 'channel'
| 'chat'
@@ -94,12 +82,9 @@ export type NodeType =
| 'message'
| 'page'
| 'record'
- | 'space'
- | 'user'
- | 'workspace';
+ | 'space';
export type NodeAttributes =
- | UserAttributes
| SpaceAttributes
| DatabaseAttributes
| ChannelAttributes
@@ -108,8 +93,7 @@ export type NodeAttributes =
| FolderAttributes
| MessageAttributes
| PageAttributes
- | RecordAttributes
- | WorkspaceAttributes;
+ | RecordAttributes;
export type Node =
| ChannelNode
@@ -120,9 +104,7 @@ export type Node =
| MessageNode
| PageNode
| RecordNode
- | SpaceNode
- | UserNode
- | WorkspaceNode;
+ | SpaceNode;
class Registry {
private models: Map<string, NodeModel> = new Map();
@@ -137,8 +119,6 @@ class Registry {
this.models.set('page', pageModel);
this.models.set('record', recordModel);
this.models.set('space', spaceModel);
- this.models.set('user', userModel);
- this.models.set('workspace', workspaceModel);
}
getModel(type: string): NodeModel {
diff --git a/packages/core/src/registry/user.ts b/packages/core/src/registry/user.ts
deleted file mode 100644
index 6cc89583..00000000
--- a/packages/core/src/registry/user.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { z } from 'zod';
-
-import { NodeModel } from './core';
-
-export const userAttributesSchema = z.object({
- type: z.literal('user'),
- name: z.string(),
- parentId: z.string(),
- email: z.string().email(),
- avatar: z.string().nullable().optional(),
- accountId: z.string(),
- role: z.enum(['owner', 'admin', 'collaborator', 'guest', 'none']),
-});
-
-export type UserAttributes = z.infer<typeof userAttributesSchema>;
-
-export const userModel: NodeModel = {
- type: 'user',
- schema: userAttributesSchema,
- getName: (_, attributes) => {
- if (attributes.type !== 'user') {
- return undefined;
- }
-
- return attributes.name;
- },
- getText: () => {
- return undefined;
- },
- canCreate: async (_, __) => {
- return false;
- },
- canUpdate: async (_, __, ___) => {
- return false;
- },
- canDelete: async (_, __) => {
- return false;
- },
-};
diff --git a/packages/core/src/registry/workspace.ts b/packages/core/src/registry/workspace.ts
deleted file mode 100644
index 6bc53569..00000000
--- a/packages/core/src/registry/workspace.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { z } from 'zod';
-
-import { NodeModel } from './core';
-
-export const workspaceAttributesSchema = z.object({
- type: z.literal('workspace'),
- name: z.string(),
- description: z.string().nullable().optional(),
- avatar: z.string().nullable().optional(),
- parentId: z.string(),
-});
-
-export type WorkspaceAttributes = z.infer<typeof workspaceAttributesSchema>;
-
-export const workspaceModel: NodeModel = {
- type: 'workspace',
- schema: workspaceAttributesSchema,
- getName: () => {
- return undefined;
- },
- getText: () => {
- return undefined;
- },
- canCreate: async (_, __) => {
- return false;
- },
- canUpdate: async (_, __, ___) => {
- return false;
- },
- canDelete: async (_, __) => {
- return false;
- },
-};
diff --git a/packages/core/src/types/messages.ts b/packages/core/src/types/messages.ts
index 9b93f815..37799eee 100644
--- a/packages/core/src/types/messages.ts
+++ b/packages/core/src/types/messages.ts
@@ -4,11 +4,10 @@ import {
ServerDeletedCollaboration,
ServerInteraction,
ServerTransaction,
+ ServerUser,
SyncConsumerType,
} from './sync';
-import { NodeType } from '../registry';
-
export type TransactionsBatchMessage = {
type: 'transactions_batch';
userId: string;
@@ -33,11 +32,16 @@ export type InteractionsBatchMessage = {
interactions: ServerInteraction[];
};
+export type UsersBatchMessage = {
+ type: 'users_batch';
+ userId: string;
+ users: ServerUser[];
+};
+
export type SyncInteractionsMessage = {
type: 'sync_interactions';
userId: string;
nodeId: string;
- nodeType: NodeType;
events: InteractionEvent[];
};
@@ -58,13 +62,6 @@ export type WorkspaceUpdatedMessage = {
workspaceId: string;
};
-export type WorkspaceUserCreatedMessage = {
- type: 'workspace_user_created';
- workspaceId: string;
- userId: string;
- accountId: string;
-};
-
export type WorkspaceDeletedMessage = {
type: 'workspace_deleted';
accountId: string;
@@ -75,9 +72,9 @@ export type Message =
| CollaborationsBatchMessage
| DeletedCollaborationsBatchMessage
| InteractionsBatchMessage
+ | UsersBatchMessage
| SyncInteractionsMessage
| InitSyncConsumerMessage
| AccountUpdatedMessage
| WorkspaceUpdatedMessage
- | WorkspaceUserCreatedMessage
| WorkspaceDeletedMessage;
diff --git a/packages/core/src/types/sync.ts b/packages/core/src/types/sync.ts
index 1a2a3df2..0f598ec9 100644
--- a/packages/core/src/types/sync.ts
+++ b/packages/core/src/types/sync.ts
@@ -1,6 +1,6 @@
import { InteractionAttributes } from './interactions';
+import { WorkspaceRole } from './workspaces';
-import { NodeType } from '../registry';
import { NodeRole } from '../registry/core';
export type SyncTransactionsInput = {
@@ -26,7 +26,6 @@ export type LocalTransaction =
export type LocalCreateTransaction = {
id: string;
nodeId: string;
- nodeType: string;
operation: 'create';
data: string;
createdAt: string;
@@ -36,7 +35,6 @@ export type LocalCreateTransaction = {
export type LocalUpdateTransaction = {
id: string;
nodeId: string;
- nodeType: string;
operation: 'update';
data: string;
createdAt: string;
@@ -46,7 +44,6 @@ export type LocalUpdateTransaction = {
export type LocalDeleteTransaction = {
id: string;
nodeId: string;
- nodeType: string;
operation: 'delete';
createdAt: string;
createdBy: string;
@@ -56,7 +53,6 @@ export type ServerCreateTransaction = {
id: string;
operation: 'create';
nodeId: string;
- nodeType: NodeType;
workspaceId: string;
data: string;
createdAt: string;
@@ -69,7 +65,6 @@ export type ServerUpdateTransaction = {
id: string;
operation: 'update';
nodeId: string;
- nodeType: NodeType;
workspaceId: string;
data: string;
createdAt: string;
@@ -82,7 +77,6 @@ export type ServerDeleteTransaction = {
id: string;
operation: 'delete';
nodeId: string;
- nodeType: NodeType;
workspaceId: string;
createdAt: string;
createdBy: string;
@@ -116,7 +110,6 @@ export type ServerCollaboration = {
export type ServerInteraction = {
userId: string;
nodeId: string;
- nodeType: NodeType;
workspaceId: string;
attributes: InteractionAttributes;
createdAt: string;
@@ -126,8 +119,23 @@ export type ServerInteraction = {
version: string;
};
+export type ServerUser = {
+ id: string;
+ workspaceId: string;
+ email: string;
+ name: string;
+ avatar: string | null;
+ role: WorkspaceRole;
+ customName: string | null;
+ customAvatar: string | null;
+ createdAt: string;
+ updatedAt: string | null;
+ version: string;
+};
+
export type SyncConsumerType =
| 'transactions'
| 'collaborations'
| 'deleted_collaborations'
- | 'interactions';
+ | 'interactions'
+ | 'users';
diff --git a/packages/core/src/types/workspaces.ts b/packages/core/src/types/workspaces.ts
index e6f1d3bf..5d8e5267 100644
--- a/packages/core/src/types/workspaces.ts
+++ b/packages/core/src/types/workspaces.ts
@@ -12,7 +12,7 @@ export enum WorkspaceStatus {
Inactive = 2,
}
-export enum WorkspaceUserStatus {
+export enum UserStatus {
Active = 1,
Inactive = 2,
}
@@ -44,24 +44,24 @@ export type WorkspaceUpdateInput = {
avatar?: string | null;
};
-export type WorkspaceUsersInviteInput = {
+export type UsersInviteInput = {
emails: string[];
role: WorkspaceRole;
};
-export type WorkspaceUserInviteResult = {
+export type UserInviteResult = {
email: string;
result: 'success' | 'error' | 'exists';
};
-export type WorkspaceUsersInviteOutput = {
- results: WorkspaceUserInviteResult[];
+export type UsersInviteOutput = {
+ results: UserInviteResult[];
};
-export type WorkspaceUserRoleUpdateInput = {
+export type UserRoleUpdateInput = {
role: WorkspaceRole;
};
-export type WorkspaceUserRoleUpdateOutput = {
+export type UserRoleUpdateOutput = {
user: NodeOutput;
};