Skip to content

Commit

Permalink
fix: do not display backend messages
Browse files Browse the repository at this point in the history
  • Loading branch information
rasulov1337 committed Dec 17, 2024
1 parent 947949f commit bf65f53
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/components/ChatWindow/ChatWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import globalStore from '../../modules/GlobalStore';
import { convertTimeToMinutesAndSeconds } from '../../modules/Utils';
import { Message } from '../../repositories/ChatRepository';

interface BackendReply {
response: string;
sent: boolean;
}

export default class ChatWindow extends BaseComponent {
private messages: Message[];
private messagesContainer: HTMLDivElement;
Expand Down Expand Up @@ -54,10 +59,7 @@ export default class ChatWindow extends BaseComponent {
console.log('Отправляем данные на сервер');
};

socket.onmessage = (event) => {
console.log(`[message] Данные получены с сервера: ${event.data}`);
this.addNewMessageElement(JSON.parse(event.data) as Message);
};
socket.onmessage = (e) => this.handleMessageReceive(e);

socket.onclose = function (event) {
if (event.wasClean) {
Expand Down Expand Up @@ -121,6 +123,7 @@ export default class ChatWindow extends BaseComponent {
content: text,
})
);

this.addNewMessageElement({
content: text,
receiverId: '',
Expand All @@ -130,6 +133,24 @@ export default class ChatWindow extends BaseComponent {
});
}

private handleMessageReceive(event: MessageEvent) {
let message;

try {
message = JSON.parse(event.data) as Message | BackendReply;
} catch {
console.warn('Received non-JSON message! Ignoring it');
return;
}

console.log(`[message] Данные получены с сервера: ${message}`);
if ('content' in message) {
this.addNewMessageElement(message);
} else {
console.log('other type of message');
}
}

private addNewMessageElement(message: Message) {
const template = document.getElementById(
'js-chat-message-template'
Expand Down

0 comments on commit bf65f53

Please sign in to comment.