52 lines
1.3 KiB
JavaScript
52 lines
1.3 KiB
JavaScript
/**
|
|
* Represents a socket message.
|
|
*/
|
|
export default class Message {
|
|
#origin;
|
|
#data;
|
|
#message;
|
|
|
|
/**
|
|
* Creates an instance of Message.
|
|
* @param {string} rawText - The raw text of the socket message.
|
|
*/
|
|
constructor(rawText) {
|
|
this.#origin = rawText;
|
|
try {
|
|
this.#data = JSON.parse(rawText.trim());
|
|
this.#message = this.#data.message;
|
|
} catch(err) {
|
|
this.#data = undefined;
|
|
this.#message = rawText;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns an iterable of the property names in the message data.
|
|
* @returns {Generator<string>} - An iterable of property names.
|
|
*/
|
|
*getProps() {
|
|
if (!this.#data || typeof(this.#data) != 'object') return;
|
|
for (const prop in this.#data) {
|
|
yield prop;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Retrieves the value of a specific property in the message data.
|
|
* @param {string} key - The key of the property.
|
|
* @returns {*} - The value associated with the specified key.
|
|
*/
|
|
get(key) {
|
|
return this.#data[key];
|
|
}
|
|
|
|
/**
|
|
* Retrieves the text content.
|
|
* @returns {string} - the text content of the socket message;
|
|
*/
|
|
text() {
|
|
return this.#data.message || '';
|
|
}
|
|
}
|