models/communities/Chat.js

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

export default class Chat {
  /**
   * Creates a Chat.
   *
   * @constructor Chat
   * @param {Object} chatMap - Chat parameters
   * @param {string} chatMap.id - ID
   * @param {string} chatMap.title - Title
   * @param {string} chatMap.avatarUrl - Avatar URL
   * @param {number} chatMap.createdAt - Creation Date
   * @param {number} chatMap.updatedAt - Updated Date
   * @param {number} chatMap.membersCount - Members count
   * @param {ChatMessage} [chatMap.lastMessage] - Last message
   * @param {User} [chatMap.otherMember] - Other member
   */
  constructor(chatMap) {
      this.id = chatMap.id || null;
      this.title = chatMap.title || null;
      this.avatarUrl = chatMap.avatarUrl || null;
      this.createdAt = chatMap.createdAt || null;
      this.updatedAt = chatMap.updatedAt || null;
      this.membersCount = chatMap.membersCount || null;

      const rawLastMessage = chatMap.lastMessage;
      if (rawLastMessage !== undefined && rawLastMessage != null) {
          const lastMessage = new ChatMessage(rawLastMessage);
          this.lastMessage = lastMessage;
      }

      const rawOtherMember = chatMap.otherMember;
      if (rawOtherMember !== undefined && rawOtherMember != null) {
          const otherMember = User.create(rawOtherMember);
          this.otherMember = otherMember;
      }

      Object.freeze(this);
  }

  /**
     * Create Chat from SGChat
     *
     * @memberof Chat
     * @param {Object} chat - SGChat
     * @returns {Chat} Chat instance
     * @ignore
     */
  static create (chat) {
    return new Chat({
        ...chat,
        lastMessage: chat.lastMessage
            ? ChatMessage.create({
                ...chat.lastMessage.content,
                ...chat.lastMessage,
                author: {
                    ...chat.lastMessage.author.publicUser,
                    verified: chat.lastMessage.author.isVerified
                }
            })
            : null,
        otherMember: chat.otherMember
            ? chat.otherMember.publicUser
            : null
    });
  }
}