meses-messaging
Version:
Meses messaging SDK in JavaScript
50 lines (44 loc) • 1.48 kB
JavaScript
class NewMessageUpdateHandler {
constructor(service, activeConversationName, identifier, callback, timeout) {
this._service = service
this._activeConversationName = activeConversationName
this._identifier = identifier
this._callback = callback
this._timeout = timeout ? timeout : 3000
this._lastCheckTime = new Date().getTime()
this._intervalId = null
}
/**
* Stop checking for update
*
* @return {Void}
*/
destroy() { clearInterval(this._intervalId) }
activate() {
const checkNewMessage = this.checkNewMessage.bind(this)
const callback = this._callback
const timeout = this._timeout
this._intervalId = setInterval(function() {
checkNewMessage()
.then(result => callback(null, result))
.catch(err => callback(err, null))
}, timeout)
}
/**
* Method for retrieving new messages
*
* @return {Promise} array of messages if fulfilled.
*/
checkNewMessage() {
const service = this._service
const activeConversationName = this._activeConversationName
const lastCheckTime = this._lastCheckTime
const now = new Date().getTime()
return new Promise(function(resolve, reject) {
service.getMessagesByInterval(activeConversationName, lastCheckTime, now)
.then(function(result) { this._lastCheckTime = now + 1; resolve(result) }.bind(this))
.catch(err => reject(err))
}.bind(this))
}
}
export default NewMessageUpdateHandler