hedgedoc/commons/src/message-transporters/mocked-backend-transport-adapter.ts
Tilman Vatteroth 753c6e593f refactor: remove isomorphic-ws
The package caused some issues while working on other features.
Mostly because bundlers have been unable to determine the correct
websocket constructor.
So I replaced it with a more object-oriented approach.

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
2023-06-02 17:40:25 +02:00

87 lines
2.2 KiB
TypeScript

/*
* SPDX-FileCopyrightText: 2023 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { RealtimeDoc } from '../y-doc-sync/index.js'
import { ConnectionState } from './message-transporter.js'
import { Message, MessageType } from './message.js'
import { TransportAdapter } from './transport-adapter.js'
/**
* Provides a transport adapter that simulates a connection with a real HedgeDoc realtime backend.
*/
export class MockedBackendTransportAdapter implements TransportAdapter {
private readonly doc: RealtimeDoc
private connected = true
private closeHandler: undefined | (() => void)
private messageHandler: undefined | ((value: Message<MessageType>) => void)
constructor(initialContent: string) {
this.doc = new RealtimeDoc(initialContent)
}
bindOnCloseEvent(handler: () => void): () => void {
this.closeHandler = handler
return () => {
this.connected = false
this.closeHandler = undefined
}
}
bindOnConnectedEvent(handler: () => void): () => void {
handler()
return () => {
//empty on purpose
}
}
bindOnErrorEvent(): () => void {
return () => {
//empty on purpose
}
}
bindOnMessageEvent(
handler: (value: Message<MessageType>) => void
): () => void {
this.messageHandler = handler
return () => {
this.messageHandler = undefined
}
}
disconnect(): void {
if (!this.connected) {
return
}
this.connected = false
this.closeHandler?.()
}
getConnectionState(): ConnectionState {
return this.connected
? ConnectionState.CONNECTED
: ConnectionState.DISCONNECTED
}
send(value: Message<MessageType>): void {
if (value.type === MessageType.NOTE_CONTENT_STATE_REQUEST) {
new Promise(() => {
this.messageHandler?.({
type: MessageType.NOTE_CONTENT_UPDATE,
payload: this.doc.encodeStateAsUpdate(value.payload)
})
}).catch((error: Error) => console.error(error))
} else if (value.type === MessageType.READY) {
new Promise(() => {
this.messageHandler?.({
type: MessageType.READY
})
}).catch((error: Error) => console.error(error))
}
}
}