models/communities/ChatMessage.js

import User from './User.js';
import MediaAttachment from './../MediaAttachment.js';

export default class ChatMessage {
    /**
    * Creates a ChatMessage
    *
    * @constructor ChatMessage
    * @param {Object} messageMap - Message parameters
    * @param {string} messageMap.id - ID
    * @param {string} [messageMap.text] - Text
    * @param {User} messageMap.author - Author
    * @param {MediaAttachment[]} [messageMap.attachments=[]] - Attachments
    * @param {Object<string, string>} [messageMap.properties={}] - Properties
    * @param {number} [messageMap.sentAt=0] - Date when it was sent
    */
    constructor(messageMap) {
        this.id = messageMap.id || null;
        this.text = messageMap.text || null;

        this.author = null;
        const rawAuthor = messageMap.author;
        if (rawAuthor !== undefined && rawAuthor != null) {
            this.author = User.create(rawAuthor);
        }

        this.attachments = [];
        const rawAttachments = messageMap.attachments;
        if (rawAttachments !== undefined && rawAttachments != null) {
            rawAttachments.forEach((attachmentMap) => {
                const attachment = new MediaAttachment(attachmentMap);
                this.attachments.push(attachment);
            });
        }

        this.properties = messageMap.properties || {};
        this.sentAt = messageMap.sentAt || 0;

        Object.freeze(this);
    }

    /**
     * Create ChatMessage from SGChatMessage
     *
     * @memberof Chat
     * @param {Object} chat - SGChatMessage
     * @returns {ChatMessage} ChatMessage instance
     * @ignore
     */
    static create (message) {
        return new ChatMessage({
            ...message,
            attachments: message.attachments
                ? message.attachments.map((attachment) => {
                    return {
                        imageUrl: attachment.imageURL,
                        videoUrl: attachment.videoURL
                    };
                })
                : null
        });
    }
}