Skip to content

Commit b222eb5

Browse files
committed
feat(backend-platform): clean code
1 parent 5dd06ff commit b222eb5

File tree

5 files changed

+46
-62
lines changed

5 files changed

+46
-62
lines changed

packages/backend-platform/src/AccountActivityService.test.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,14 @@ describe('AccountActivityService', () => {
7878
// Mock messenger
7979
mockMessenger = {
8080
registerActionHandler: jest.fn(),
81+
registerMethodActionHandlers: jest.fn(),
8182
unregisterActionHandler: jest.fn(),
8283
registerInitialEventPayload: jest.fn(),
8384
publish: jest.fn(),
8485
call: jest.fn(),
8586
subscribe: jest.fn(),
8687
unsubscribe: jest.fn(),
88+
clearEventSubscriptions: jest.fn(),
8789
} as any;
8890

8991
// Mock selected account

packages/backend-platform/src/AccountActivityService.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -555,8 +555,6 @@ export class AccountActivityService {
555555
}
556556
}
557557
});
558-
559-
console.log('AccountActivityService: System notification handlers set up successfully');
560558
} catch (error) {
561559
console.error('Failed to set up system notification handlers:', error);
562560
}

packages/backend-platform/src/WebSocketService.test.ts

Lines changed: 43 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ const setupWebSocketService = ({
224224
// Create mock messenger with all required methods
225225
const mockMessenger = {
226226
registerActionHandler: jest.fn(),
227+
registerMethodActionHandlers: jest.fn(),
227228
registerInitialEventPayload: jest.fn(),
228229
publish: jest.fn(),
229230
call: jest.fn(),
@@ -232,7 +233,7 @@ const setupWebSocketService = ({
232233
} as any as jest.Mocked<WebSocketServiceMessenger>;
233234

234235
// Default test options (shorter timeouts for faster tests)
235-
const defaultOptions: WebSocketServiceOptions = {
236+
const defaultOptions = {
236237
url: TEST_CONSTANTS.WS_URL,
237238
timeout: TEST_CONSTANTS.TIMEOUT_MS,
238239
reconnectDelay: TEST_CONSTANTS.RECONNECT_DELAY,
@@ -368,14 +369,28 @@ describe('WebSocketService', () => {
368369
mockWebSocketOptions: { autoConnect: false }, // This prevents any connection
369370
});
370371

371-
// Wait for the automatic init() from constructor to complete and fail
372+
// Service should start in disconnected state since we removed auto-init
373+
expect(service.getConnectionInfo().state).toBe(WebSocketState.DISCONNECTED);
374+
375+
// Use expect.assertions to ensure error handling is tested
376+
expect.assertions(4);
377+
378+
// Start connection and then advance timers to trigger timeout
379+
const connectPromise = service.connect();
380+
381+
// Handle the promise rejection properly
382+
connectPromise.catch(() => {
383+
// Expected rejection - do nothing to avoid unhandled promise warning
384+
});
385+
372386
await completeAsyncOperations(TEST_CONSTANTS.TIMEOUT_MS + 50);
373387

374-
// Verify we're in error state from the failed init()
388+
// Now check that the connection failed as expected
389+
await expect(connectPromise).rejects.toThrow(`Failed to connect to WebSocket: Connection timeout after ${TEST_CONSTANTS.TIMEOUT_MS}ms`);
390+
391+
// Verify we're in error state from the failed connection attempt
375392
expect(service.getConnectionInfo().state).toBe(WebSocketState.ERROR);
376393

377-
// The timeout behavior is already tested by the constructor's init() call
378-
// We can verify that the error was due to timeout by checking the last error
379394
const info = service.getConnectionInfo();
380395
expect(info.lastError).toContain(`Connection timeout after ${TEST_CONSTANTS.TIMEOUT_MS}ms`);
381396

@@ -467,12 +482,12 @@ describe('WebSocketService', () => {
467482
}, 10000);
468483

469484
it('should throw error when not connected', async () => {
470-
const { service, completeAsyncOperations, cleanup } = setupWebSocketService({
485+
const { service, cleanup } = setupWebSocketService({
471486
mockWebSocketOptions: { autoConnect: false },
472487
});
473488

474-
// Wait for automatic init() to fail and transition to error state
475-
await completeAsyncOperations(150);
489+
// Service starts in disconnected state since we removed auto-init
490+
expect(service.getConnectionInfo().state).toBe(WebSocketState.DISCONNECTED);
476491

477492
const mockCallback = jest.fn();
478493

@@ -481,7 +496,7 @@ describe('WebSocketService', () => {
481496
channels: ['test-channel'],
482497
callback: mockCallback,
483498
})
484-
).rejects.toThrow('Cannot create subscription(s) test-channel: WebSocket is error');
499+
).rejects.toThrow('Cannot create subscription(s) test-channel: WebSocket is disconnected');
485500

486501
cleanup();
487502
});
@@ -803,8 +818,8 @@ describe('WebSocketService', () => {
803818
},
804819
} satisfies ClientRequestMessage;
805820

806-
// Should throw when not connected (service starts in connecting state)
807-
await expect(service.sendMessage(testMessage)).rejects.toThrow('Cannot send message: WebSocket is connecting');
821+
// Should throw when not connected (service starts in disconnected state)
822+
await expect(service.sendMessage(testMessage)).rejects.toThrow('Cannot send message: WebSocket is disconnected');
808823

809824
cleanup();
810825
});
@@ -998,8 +1013,24 @@ describe('WebSocketService', () => {
9981013
mockWebSocketOptions: { autoConnect: false },
9991014
});
10001015

1001-
// Wait for automatic init() to fail
1016+
// Service should start in disconnected state
1017+
expect(service.getConnectionInfo().state).toBe(WebSocketState.DISCONNECTED);
1018+
1019+
// Use expect.assertions to ensure error handling is tested
1020+
expect.assertions(5);
1021+
1022+
// Start connection and then advance timers to trigger timeout
1023+
const connectPromise = service.connect();
1024+
1025+
// Handle the promise rejection properly
1026+
connectPromise.catch(() => {
1027+
// Expected rejection - do nothing to avoid unhandled promise warning
1028+
});
1029+
10021030
await completeAsyncOperations(TEST_CONSTANTS.TIMEOUT_MS + 50);
1031+
1032+
// Wait for connection to fail
1033+
await expect(connectPromise).rejects.toThrow(`Failed to connect to WebSocket: Connection timeout after ${TEST_CONSTANTS.TIMEOUT_MS}ms`);
10031034

10041035
const info = service.getConnectionInfo();
10051036
expect(info.state).toBe(WebSocketState.ERROR);

packages/backend-platform/src/WebsocketService-method-action-types.ts

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,6 @@
55

66
import type { WebSocketService } from './WebsocketService';
77

8-
/**
9-
* Initializes and connects the WebSocket service
10-
*
11-
* @returns Promise that resolves when initialization is complete
12-
*/
13-
export type WebSocketServiceInitAction = {
14-
type: `WebSocketService:init`;
15-
handler: WebSocketService['init'];
16-
};
17-
188
/**
199
* Establishes WebSocket connection
2010
*
@@ -144,7 +134,6 @@ export type WebSocketServiceGetChannelCallbacksAction = {
144134
* Union of all WebSocketService action types.
145135
*/
146136
export type WebSocketServiceMethodActions =
147-
| WebSocketServiceInitAction
148137
| WebSocketServiceConnectAction
149138
| WebSocketServiceDisconnectAction
150139
| WebSocketServiceSendMessageAction

packages/backend-platform/src/WebsocketService.ts

Lines changed: 1 addition & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import type { WebSocketServiceMethodActions } from './WebsocketService-method-ac
55
const SERVICE_NAME = 'BackendWebSocketService' as const;
66

77
const MESSENGER_EXPOSED_METHODS = [
8-
'init',
98
'connect',
109
'disconnect',
1110
'sendMessage',
@@ -284,27 +283,6 @@ export class WebSocketService {
284283
this,
285284
MESSENGER_EXPOSED_METHODS,
286285
);
287-
288-
this.init().catch((error) => {
289-
console.error('WebSocket service initialization failed:', error);
290-
});
291-
}
292-
293-
/**
294-
* Initializes and connects the WebSocket service
295-
*
296-
* @returns Promise that resolves when initialization is complete
297-
*/
298-
async init(): Promise<void> {
299-
try {
300-
await this.connect();
301-
} catch (error) {
302-
const errorMessage = this.#getErrorMessage(error);
303-
304-
throw new Error(
305-
`WebSocket service initialization failed: ${errorMessage}`,
306-
);
307-
}
308286
}
309287

310288
/**
@@ -417,7 +395,7 @@ export class WebSocketService {
417395
throw new Error(`Cannot send request: WebSocket is ${this.#state}`);
418396
}
419397

420-
const requestId = this.#generateMessageId();
398+
const requestId = uuidV4();
421399
const requestMessage: ClientRequestMessage = {
422400
event: message.event,
423401
data: {
@@ -547,8 +525,6 @@ export class WebSocketService {
547525

548526
this.#channelCallbacks.set(options.channelName, channelCallback);
549527

550-
console.log(`Added channel callback for '${options.channelName}'`);
551-
552528
return options.channelName;
553529
}
554530

@@ -583,9 +559,6 @@ export class WebSocketService {
583559
this.#clearTimers();
584560
this.#clearSubscriptions();
585561

586-
// Clear channel callbacks
587-
this.#channelCallbacks.clear();
588-
589562
// Clear any pending connection promise
590563
this.#connectionPromise = null;
591564

@@ -1156,15 +1129,6 @@ export class WebSocketService {
11561129
}
11571130
}
11581131

1159-
/**
1160-
* Generates a unique message ID using UUID v4
1161-
*
1162-
* @returns Unique message identifier (UUID v4)
1163-
*/
1164-
#generateMessageId(): string {
1165-
return uuidV4();
1166-
}
1167-
11681132
/**
11691133
* Gets human-readable close reason from RFC 6455 close code
11701134
*

0 commit comments

Comments
 (0)