2016-07-28 05:29:35 +08:00
|
|
|
import _ from 'underscore'
|
2016-12-03 03:44:41 +08:00
|
|
|
import {NylasLongConnection, DatabaseStore} from 'nylas-exports'
|
2016-07-27 17:56:55 +08:00
|
|
|
|
2016-11-29 09:33:14 +08:00
|
|
|
class DeltaStreamingConnection extends NylasLongConnection {
|
2016-07-27 17:56:55 +08:00
|
|
|
constructor(api, accountId, opts = {}) {
|
2016-11-29 04:05:41 +08:00
|
|
|
opts.throttleResultsInterval = 1000
|
2016-07-27 17:56:55 +08:00
|
|
|
opts.closeIfDataStopsInterval = 15 * 1000
|
|
|
|
super(api, accountId, opts)
|
|
|
|
|
2016-12-01 06:55:09 +08:00
|
|
|
const {getCursor, setCursor} = opts
|
2016-07-27 17:56:55 +08:00
|
|
|
this._getCursor = getCursor
|
|
|
|
this._setCursor = setCursor
|
|
|
|
|
2016-07-28 05:29:35 +08:00
|
|
|
// Update cursor when deltas received
|
|
|
|
this.onDeltas((deltas) => {
|
2016-12-01 06:55:09 +08:00
|
|
|
if (opts.onDeltas) opts.onDeltas(deltas);
|
2016-07-28 05:29:35 +08:00
|
|
|
const last = _.last(deltas)
|
|
|
|
this._setCursor(last.cursor)
|
|
|
|
})
|
2016-07-27 17:56:55 +08:00
|
|
|
}
|
|
|
|
|
2016-12-03 03:44:41 +08:00
|
|
|
_deltaStreamingPath(cursor) {
|
2016-12-02 10:42:10 +08:00
|
|
|
return `/delta/streaming?cursor=${cursor}`
|
2016-07-27 17:56:55 +08:00
|
|
|
}
|
|
|
|
|
2016-07-28 05:29:35 +08:00
|
|
|
onError(err) {
|
2017-02-01 04:07:17 +08:00
|
|
|
if (err.message.includes('Invalid cursor')) {
|
2016-12-03 03:44:41 +08:00
|
|
|
const error = new Error('Delta Connection: Cursor is invalid. Need to blow away local cache.');
|
|
|
|
this._setCursor(0)
|
2016-07-28 05:29:35 +08:00
|
|
|
DatabaseStore._handleSetupError(error)
|
|
|
|
}
|
2017-02-01 04:07:17 +08:00
|
|
|
this._onError(err)
|
2016-07-28 05:29:35 +08:00
|
|
|
}
|
|
|
|
|
2016-07-27 17:56:55 +08:00
|
|
|
onDeltas(callback) {
|
|
|
|
return this.onResults(callback)
|
|
|
|
}
|
|
|
|
|
|
|
|
start() {
|
2016-12-03 03:44:41 +08:00
|
|
|
this._path = this._deltaStreamingPath(this._getCursor() || 0)
|
|
|
|
super.start()
|
2016-07-27 17:56:55 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-29 09:33:14 +08:00
|
|
|
export default DeltaStreamingConnection
|