all files / src/core/ Message.js

0% Statements 0/16
0% Branches 0/2
0% Functions 0/7
0% Lines 0/16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89                                                                                                                                                                                 
import * as DataSync from './util/DataSync';
import * as Log from './util/Log';
 
import cache from './util/cache';
/**
 * Instant Message
 * @public
 */
export default class Message {
	/**
	 * Create a message
	 * @param {Webcom/api.DataSnapshot|Object} snapData The data snapshot
	 * @param {string} roomId The message's room id
	 * @access protected
	 */
	constructor(snapData, roomId) {
		const values = Object.assign({}, snapData.val());
		/**
		 * The message unique id
		 * @type {string}
		 */
		this.uid = snapData.name();
		/**
		 * The room uid
		 * @type {string}
		 */
		this.roomId = roomId;
		/**
		 * The message
		 * @type {string}
		 */
		this.text = values.text;
		/**
		 * The message sender
		 * @type {string}
		 */
		this.from = values.from;
		/**
		 * Joined date
		 * @type {number}
		 */
		this._created = values._created;
	}
 
	/**
	 * Edit the text message. Only the sender or moderator/owner of the room can edit a message.
	 * @param {string} newText The new message
	 * @returns {Promise<Message>}
	 */
	edit(newText) {
		return DataSync.update(`/rooms/${this.roomId}/messages/${this.uid}`, {text: newText})
			.then(() => {
				this.text = newText;
				return this;
			})
			.catch(Log.r('Message~edit'));
	}
 
	/**
	 * Remove the text message. Only the sender or moderator/owner of the room can remove a message.
	 * @returns {Promise}
	 */
	remove() {
		return DataSync.remove(`/rooms/${this.roomId}/messages/${this.uid}`)
			.catch(Log.r('Message~remove'));
	}
 
	/**
	 *
	 * @param {Room} room The room to send the message to
	 * @param {string} text The message
	 * @return {Promise<Message>}
	 */
	static send(room, text) {
		if(!cache.user) {
			return Promise.reject(new Error('Cannot send a message to the Room without a User being logged in.'));
		}
		const data = {
			from: cache.user.uid,
			_created: DataSync.ts(),
			text
		};
		return DataSync.push(`_/rooms/${room.uid}/messages`, data)
			.then(pushRef => DataSync.get(`_/rooms/${room.uid}/messages/${pushRef.name()}`))
			.then(snapData => new Message(snapData, room.uid))
			.catch(Log.r('Message#send'));
	}
}