Skip to content

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

Refactor http client

Hakan Shehu21531f4a0fc1
diff --git a/apps/desktop/src/main/mutations/account-update.ts b/apps/desktop/src/main/mutations/account-update.ts
index 0deeec45..12e99003 100644
--- a/apps/desktop/src/main/mutations/account-update.ts
+++ b/apps/desktop/src/main/mutations/account-update.ts
@@ -41,8 +41,7 @@ export class AccountUpdateMutationHandler
avatar: input.avatar,
},
{
- serverDomain: server.domain,
- serverAttributes: server.attributes,
+ domain: server.domain,
token: account.token,
}
);
diff --git a/apps/desktop/src/main/mutations/avatar-upload.ts b/apps/desktop/src/main/mutations/avatar-upload.ts
index ffa0c48f..821ab7ae 100644
--- a/apps/desktop/src/main/mutations/avatar-upload.ts
+++ b/apps/desktop/src/main/mutations/avatar-upload.ts
@@ -42,8 +42,7 @@ export class AvatarUploadMutationHandler
'/v1/avatars',
formData,
{
- serverDomain: credentials.domain,
- serverAttributes: credentials.attributes,
+ domain: credentials.domain,
token: credentials.token,
headers: formData.getHeaders(),
}
diff --git a/apps/desktop/src/main/mutations/email-login.ts b/apps/desktop/src/main/mutations/email-login.ts
index fbfd4fd8..57cdcf2b 100644
--- a/apps/desktop/src/main/mutations/email-login.ts
+++ b/apps/desktop/src/main/mutations/email-login.ts
@@ -34,8 +34,7 @@ export class EmailLoginMutationHandler
password: input.password,
},
{
- serverDomain: server.domain,
- serverAttributes: server.attributes,
+ domain: server.domain,
}
);
diff --git a/apps/desktop/src/main/mutations/email-register.ts b/apps/desktop/src/main/mutations/email-register.ts
index ba104be6..a7096672 100644
--- a/apps/desktop/src/main/mutations/email-register.ts
+++ b/apps/desktop/src/main/mutations/email-register.ts
@@ -35,8 +35,7 @@ export class EmailRegisterMutationHandler
password: input.password,
},
{
- serverDomain: server.domain,
- serverAttributes: server.attributes,
+ domain: server.domain,
}
);
diff --git a/apps/desktop/src/main/mutations/server-create.ts b/apps/desktop/src/main/mutations/server-create.ts
index 19b0a906..6bfbb9af 100644
--- a/apps/desktop/src/main/mutations/server-create.ts
+++ b/apps/desktop/src/main/mutations/server-create.ts
@@ -1,12 +1,11 @@
-import axios from 'axios';
import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
import {
ServerCreateMutationInput,
ServerCreateMutationOutput,
} from '@/shared/mutations/server-create';
-import { ServerConfig } from '@/shared/types/servers';
import { eventBus } from '@/shared/lib/event-bus';
+import { serverService } from '../services/server-service';
export class ServerCreateMutationHandler
implements MutationHandler<ServerCreateMutationInput>
@@ -14,19 +13,22 @@ export class ServerCreateMutationHandler
async handleMutation(
input: ServerCreateMutationInput
): Promise<ServerCreateMutationOutput> {
- const { data } = await axios.get<ServerConfig>(
- `http://${input.domain}/v1/config`
- );
+ const config = await serverService.fetchServerConfig(input.domain);
+ if (!config) {
+ return {
+ success: false,
+ };
+ }
const createdAt = new Date();
await databaseService.appDatabase
.insertInto('servers')
.values({
domain: input.domain,
- name: data.name,
- avatar: data.avatar,
- attributes: JSON.stringify(data.attributes),
- version: data.version,
+ name: config.name,
+ avatar: config.avatar,
+ attributes: JSON.stringify(config.attributes),
+ version: config.version,
created_at: createdAt.toISOString(),
})
.execute();
@@ -35,10 +37,10 @@ export class ServerCreateMutationHandler
type: 'server_created',
server: {
domain: input.domain,
- name: data.name,
- avatar: data.avatar,
- attributes: data.attributes,
- version: data.version,
+ name: config.name,
+ avatar: config.avatar,
+ attributes: config.attributes,
+ version: config.version,
createdAt,
lastSyncedAt: null,
},
diff --git a/apps/desktop/src/main/mutations/workspace-create.ts b/apps/desktop/src/main/mutations/workspace-create.ts
index bba05823..3118513a 100644
--- a/apps/desktop/src/main/mutations/workspace-create.ts
+++ b/apps/desktop/src/main/mutations/workspace-create.ts
@@ -42,8 +42,7 @@ export class WorkspaceCreateMutationHandler
avatar: input.avatar,
},
{
- serverDomain: server.domain,
- serverAttributes: server.attributes,
+ domain: server.domain,
token: account.token,
}
);
diff --git a/apps/desktop/src/main/mutations/workspace-update.ts b/apps/desktop/src/main/mutations/workspace-update.ts
index b3694f06..9e737056 100644
--- a/apps/desktop/src/main/mutations/workspace-update.ts
+++ b/apps/desktop/src/main/mutations/workspace-update.ts
@@ -42,8 +42,7 @@ export class WorkspaceUpdateMutationHandler
avatar: input.avatar,
},
{
- serverDomain: server.domain,
- serverAttributes: server.attributes,
+ domain: server.domain,
token: account.token,
}
);
diff --git a/apps/desktop/src/main/mutations/workspace-user-role-update.ts b/apps/desktop/src/main/mutations/workspace-user-role-update.ts
index 0bc5f1d6..67cdb6dc 100644
--- a/apps/desktop/src/main/mutations/workspace-user-role-update.ts
+++ b/apps/desktop/src/main/mutations/workspace-user-role-update.ts
@@ -58,8 +58,7 @@ export class WorkspaceUserRoleUpdateMutationHandler
role: input.role,
},
{
- serverDomain: server.domain,
- serverAttributes: server.attributes,
+ domain: server.domain,
token: account.token,
}
);
diff --git a/apps/desktop/src/main/mutations/workspace-users-invite.ts b/apps/desktop/src/main/mutations/workspace-users-invite.ts
index 986f2b82..9b13a3ed 100644
--- a/apps/desktop/src/main/mutations/workspace-users-invite.ts
+++ b/apps/desktop/src/main/mutations/workspace-users-invite.ts
@@ -60,8 +60,7 @@ export class WorkspaceUsersInviteMutationHandler
role: input.role,
},
{
- serverDomain: server.domain,
- serverAttributes: server.attributes,
+ domain: server.domain,
token: account.token,
}
);
diff --git a/apps/desktop/src/main/queries/server-list.ts b/apps/desktop/src/main/queries/server-list.ts
index 6ed94bd5..03656dad 100644
--- a/apps/desktop/src/main/queries/server-list.ts
+++ b/apps/desktop/src/main/queries/server-list.ts
@@ -24,6 +24,14 @@ export class ServerListQueryHandler
hasChanges: true,
result: newServers,
};
+ } else if (event.type === 'server_updated') {
+ const newServers = output.map((server) =>
+ server.domain === event.server.domain ? event.server : server
+ );
+ return {
+ hasChanges: true,
+ result: newServers,
+ };
}
return {
diff --git a/apps/desktop/src/main/services/account-service.ts b/apps/desktop/src/main/services/account-service.ts
index 5cff2ae1..61e9a331 100644
--- a/apps/desktop/src/main/services/account-service.ts
+++ b/apps/desktop/src/main/services/account-service.ts
@@ -39,8 +39,7 @@ class AccountService {
const { data, status } = await httpClient.get<AccountSyncOutput>(
'/v1/accounts/sync',
{
- serverDomain: server.domain,
- serverAttributes: server.attributes,
+ domain: server.domain,
token: account.token,
}
);
@@ -213,8 +212,7 @@ class AccountService {
try {
const { status } = await httpClient.delete(`/v1/accounts/logout`, {
- serverDomain: deletedToken.domain,
- serverAttributes: deletedToken.attributes,
+ domain: deletedToken.domain,
token: deletedToken.token,
});
diff --git a/apps/desktop/src/main/services/avatar-service.ts b/apps/desktop/src/main/services/avatar-service.ts
index c0187c70..059b012b 100644
--- a/apps/desktop/src/main/services/avatar-service.ts
+++ b/apps/desktop/src/main/services/avatar-service.ts
@@ -31,8 +31,7 @@ class AvatarService {
}
const response = await httpClient.get<any>(`/v1/avatars/${avatarId}`, {
- serverDomain: credentials.domain,
- serverAttributes: credentials.attributes,
+ domain: credentials.domain,
token: credentials.token,
responseType: 'stream',
});
diff --git a/apps/desktop/src/main/services/file-service.ts b/apps/desktop/src/main/services/file-service.ts
index f88f1a2b..a38b51de 100644
--- a/apps/desktop/src/main/services/file-service.ts
+++ b/apps/desktop/src/main/services/file-service.ts
@@ -155,8 +155,7 @@ class FileService {
`/v1/files/${credentials.workspaceId}/${upload.node_id}`,
{},
{
- serverDomain: credentials.serverDomain,
- serverAttributes: credentials.serverAttributes,
+ domain: credentials.serverDomain,
token: credentials.token,
}
);
@@ -273,8 +272,7 @@ class FileService {
const { data } = await httpClient.get<ServerFileDownloadResponse>(
`/v1/files/${credentials.workspaceId}/${download.node_id}`,
{
- serverDomain: credentials.serverDomain,
- serverAttributes: credentials.serverAttributes,
+ domain: credentials.serverDomain,
token: credentials.token,
}
);
diff --git a/apps/desktop/src/main/services/server-service.ts b/apps/desktop/src/main/services/server-service.ts
index 6ee7f7ba..9978fb49 100644
--- a/apps/desktop/src/main/services/server-service.ts
+++ b/apps/desktop/src/main/services/server-service.ts
@@ -1,5 +1,6 @@
import axios from 'axios';
-import { Server, ServerConfig } from '@/shared/types/servers';
+import { Server } from '@/shared/types/servers';
+import { ServerConfig } from '@colanode/core';
import { databaseService } from '@/main/data/database-service';
import { mapServer } from '@/main/utils';
import { eventBus } from '@/shared/lib/event-bus';
@@ -32,7 +33,7 @@ class ServerService {
}
private async syncServer(server: Server) {
- const config = await this.fetchServerConfig(server);
+ const config = await this.fetchServerConfig(server.domain);
const existingState = this.states.get(server.domain);
const newState: ServerState = {
@@ -57,10 +58,32 @@ class ServerService {
console.log(
`Server ${server.domain} is ${isAvailable ? 'available' : 'unavailable'}`
);
+
+ if (config) {
+ const updatedServer = await databaseService.appDatabase
+ .updateTable('servers')
+ .returningAll()
+ .set({
+ last_synced_at: new Date().toISOString(),
+ attributes: JSON.stringify(config.attributes),
+ avatar: config.avatar,
+ name: config.name,
+ version: config.version,
+ })
+ .where('domain', '=', server.domain)
+ .executeTakeFirst();
+
+ if (updatedServer) {
+ eventBus.publish({
+ type: 'server_updated',
+ server: mapServer(updatedServer),
+ });
+ }
+ }
}
- private async fetchServerConfig(server: Server) {
- const baseUrl = this.buildApiBaseUrl(server.domain);
+ public async fetchServerConfig(domain: string) {
+ const baseUrl = this.buildApiBaseUrl(domain);
const configUrl = `${baseUrl}/v1/config`;
try {
const { status, data } = await axios.get<ServerConfig>(configUrl);
diff --git a/apps/desktop/src/main/services/socket-connection.ts b/apps/desktop/src/main/services/socket-connection.ts
index 2af0ab6f..faf6c5de 100644
--- a/apps/desktop/src/main/services/socket-connection.ts
+++ b/apps/desktop/src/main/services/socket-connection.ts
@@ -1,16 +1,9 @@
import { WebSocket } from 'ws';
import { BackoffCalculator } from '@/shared/lib/backoff-calculator';
import { Message } from '@colanode/core';
-import { SelectAccount, SelectServer } from '@/main/data/app/schema';
-import { ServerAttributes } from '@/shared/types/servers';
+import { SelectAccount } from '@/main/data/app/schema';
import { mutationService } from '@/main/services/mutation-service';
-const buildSynapseUrl = (server: SelectServer, deviceId: string) => {
- const attributes = JSON.parse(server.attributes) as ServerAttributes;
- const protocol = attributes?.insecure ? 'ws' : 'wss';
- return `${protocol}://${server.domain}/v1/synapse?device_id=${deviceId}`;
-};
-
export class SocketConnection {
private readonly synapseUrl: string;
private readonly account: SelectAccount;
diff --git a/apps/desktop/src/main/services/workspace-service.ts b/apps/desktop/src/main/services/workspace-service.ts
index 9195c010..b231b4b1 100644
--- a/apps/desktop/src/main/services/workspace-service.ts
+++ b/apps/desktop/src/main/services/workspace-service.ts
@@ -134,8 +134,7 @@ class WorkspaceService {
changes: changesToSync,
},
{
- serverDomain: workspace.domain,
- serverAttributes: workspace.attributes,
+ domain: workspace.domain,
token: workspace.token,
}
);
diff --git a/apps/desktop/src/shared/lib/http-client.ts b/apps/desktop/src/shared/lib/http-client.ts
index 40251570..be148e4c 100644
--- a/apps/desktop/src/shared/lib/http-client.ts
+++ b/apps/desktop/src/shared/lib/http-client.ts
@@ -1,10 +1,9 @@
+import { serverService } from '@/main/services/server-service';
import { BackoffCalculator } from '@/shared/lib/backoff-calculator';
-import { ServerAttributes } from '@/shared/types/servers';
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
interface HttpClientRequestConfig extends AxiosRequestConfig {
- serverDomain: string;
- serverAttributes: string | ServerAttributes;
+ domain: string;
token?: string | null;
}
@@ -18,10 +17,10 @@ class HttpClient {
path: string,
config: HttpClientRequestConfig
): Promise<AxiosResponse<T>> {
- if (this.backoffs.has(config.serverDomain)) {
- const backoff = this.backoffs.get(config.serverDomain);
+ if (this.backoffs.has(config.domain)) {
+ const backoff = this.backoffs.get(config.domain);
if (!backoff?.canRetry()) {
- throw new Error(`Backoff in progress for key: ${config.serverDomain}`);
+ throw new Error(`Backoff in progress for key: ${config.domain}`);
}
}
@@ -34,19 +33,19 @@ class HttpClient {
});
// Reset backoff if successful
- if (this.backoffs.has(config.serverDomain)) {
- this.backoffs.get(config.serverDomain)?.reset();
+ if (this.backoffs.has(config.domain)) {
+ this.backoffs.get(config.domain)?.reset();
}
return response;
} catch (error: any) {
// If error is related to server availability, increase backoff
if (this.isServerError(error)) {
- if (!this.backoffs.has(config.serverDomain)) {
- this.backoffs.set(config.serverDomain, new BackoffCalculator());
+ if (!this.backoffs.has(config.domain)) {
+ this.backoffs.set(config.domain, new BackoffCalculator());
}
- const backoff = this.backoffs.get(config.serverDomain);
+ const backoff = this.backoffs.get(config.domain);
backoff?.increaseError();
}
@@ -63,12 +62,7 @@ class HttpClient {
}
private buildAxiosInstance(config: HttpClientRequestConfig): AxiosInstance {
- const parsedAttributes: ServerAttributes =
- typeof config.serverAttributes === 'string'
- ? JSON.parse(config.serverAttributes)
- : config.serverAttributes;
- const protocol = parsedAttributes?.insecure ? 'http' : 'https';
- const baseURL = `${protocol}://${config.serverDomain}`;
+ const baseURL = serverService.buildApiBaseUrl(config.domain);
const instance = axios.create({ baseURL });
if (config.token) {
diff --git a/apps/desktop/src/shared/types/events.ts b/apps/desktop/src/shared/types/events.ts
index e19b3a31..53de5a36 100644
--- a/apps/desktop/src/shared/types/events.ts
+++ b/apps/desktop/src/shared/types/events.ts
@@ -57,6 +57,11 @@ export type ServerCreatedEvent = {
server: Server;
};
+export type ServerUpdatedEvent = {
+ type: 'server_updated';
+ server: Server;
+};
+
export type UserNodeCreatedEvent = {
type: 'user_node_created';
userId: string;
@@ -138,6 +143,7 @@ export type Event =
| WorkspaceUpdatedEvent
| WorkspaceDeletedEvent
| ServerCreatedEvent
+ | ServerUpdatedEvent
| UserNodeCreatedEvent
| UserNodeUpdatedEvent
| DownloadCreatedEvent
diff --git a/apps/desktop/src/shared/types/servers.ts b/apps/desktop/src/shared/types/servers.ts
index 25dfdabb..9d036b76 100644
--- a/apps/desktop/src/shared/types/servers.ts
+++ b/apps/desktop/src/shared/types/servers.ts
@@ -1,3 +1,5 @@
+import { ServerAttributes } from '@colanode/core';
+
export type Server = {
domain: string;
name: string;
@@ -7,14 +9,3 @@ export type Server = {
createdAt: Date;
lastSyncedAt: Date | null;
};
-
-export type ServerAttributes = {
- insecure?: string;
-};
-
-export type ServerConfig = {
- name: string;
- avatar: string;
- version: string;
- attributes: ServerAttributes;
-};
diff --git a/apps/server/src/routes/config.ts b/apps/server/src/routes/config.ts
index 88f42cb6..eb28fad2 100644
--- a/apps/server/src/routes/config.ts
+++ b/apps/server/src/routes/config.ts
@@ -1,14 +1,15 @@
+import { ServerConfig } from '@colanode/core';
import { Router, Request, Response } from 'express';
export const configRouter = Router();
configRouter.get('/', async (_: Request, res: Response) => {
- res.status(200).json({
+ const config: ServerConfig = {
name: 'Colanode Cloud',
avatar: '',
version: '0.1.0',
- attributes: {
- insecure: true,
- },
- });
+ attributes: {},
+ };
+
+ res.status(200).json(config);
});
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d749dba1..9f0b5320 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -22,3 +22,4 @@ export * from './types/nodes';
export * from './types/sync';
export * from './types/accounts';
export * from './types/messages';
+export * from './types/servers';
diff --git a/packages/core/src/types/servers.ts b/packages/core/src/types/servers.ts
new file mode 100644
index 00000000..1b8089cf
--- /dev/null
+++ b/packages/core/src/types/servers.ts
@@ -0,0 +1,8 @@
+export type ServerConfig = {
+ name: string;
+ avatar: string;
+ version: string;
+ attributes: ServerAttributes;
+};
+
+export type ServerAttributes = {};