OpChan/src/lib/waku/CodecManager.ts

80 lines
2.1 KiB
TypeScript
Raw Normal View History

2025-08-30 18:34:50 +05:30
import { IDecodedMessage, IDecoder, IEncoder, LightNode } from '@waku/sdk';
2025-09-03 15:01:57 +05:30
import { MessageType, UserProfileUpdateMessage } from '../../types/waku';
2025-08-29 16:30:19 +05:30
import {
CellMessage,
PostMessage,
CommentMessage,
VoteMessage,
2025-08-29 17:08:04 +05:30
} from '../../types/waku';
import { CONTENT_TOPIC } from './constants';
2025-08-29 14:53:02 +05:30
import { OpchanMessage } from '@/types/forum';
2025-04-16 14:45:27 +05:30
2025-08-29 16:30:19 +05:30
export class CodecManager {
private encoder: IEncoder;
private decoder: IDecoder<IDecodedMessage>;
2025-08-29 15:43:10 +05:30
2025-08-29 16:30:19 +05:30
constructor(private node: LightNode) {
this.encoder = this.node.createEncoder({ contentTopic: CONTENT_TOPIC });
this.decoder = this.node.createDecoder({ contentTopic: CONTENT_TOPIC });
2025-08-29 16:30:19 +05:30
}
2025-08-29 16:30:19 +05:30
/**
* Encode a message for transmission
*/
encodeMessage(message: OpchanMessage): Uint8Array {
const messageJson = JSON.stringify(message);
return new TextEncoder().encode(messageJson);
}
/**
* Decode a received message
*/
decodeMessage(payload: Uint8Array): OpchanMessage {
const messageJson = new TextDecoder().decode(payload);
const message = JSON.parse(messageJson) as OpchanMessage;
switch (message.type) {
case MessageType.CELL:
return message as CellMessage;
case MessageType.POST:
return message as PostMessage;
case MessageType.COMMENT:
return message as CommentMessage;
case MessageType.VOTE:
return message as VoteMessage;
2025-09-03 15:01:57 +05:30
case MessageType.USER_PROFILE_UPDATE:
return message as UserProfileUpdateMessage;
2025-08-29 16:30:19 +05:30
default:
throw new Error(`Unknown message type: ${message}`);
}
}
/**
* Get the single encoder for all message types
2025-08-29 16:30:19 +05:30
*/
getEncoder(): IEncoder {
return this.encoder;
2025-08-29 16:30:19 +05:30
}
2025-08-29 16:30:19 +05:30
/**
* Get the single decoder for all message types
2025-08-29 16:30:19 +05:30
*/
getDecoder(): IDecoder<IDecodedMessage> {
return this.decoder;
2025-08-29 16:30:19 +05:30
}
2025-08-29 16:30:19 +05:30
/**
* Get all decoders (returns single decoder in array for compatibility)
2025-08-29 16:30:19 +05:30
*/
getAllDecoders(): IDecoder<IDecodedMessage>[] {
return [this.decoder];
}
2025-08-29 16:30:19 +05:30
/**
* Get decoders for specific message types (returns single decoder for all types)
2025-08-29 16:30:19 +05:30
*/
getDecoders(_messageTypes: MessageType[]): IDecoder<IDecodedMessage>[] {
return [this.decoder];
2025-08-29 16:30:19 +05:30
}
}