2015-10-10 03:40:36 +08:00
|
|
|
_ = require 'underscore'
|
|
|
|
{NylasStore, DatabaseStore} = require 'nylas-exports'
|
|
|
|
|
|
|
|
|
|
|
|
class RefreshingJSONCache
|
|
|
|
|
2017-03-23 05:34:03 +08:00
|
|
|
constructor: ({@key, @version, @refreshInterval, @maxRefreshInterval}) ->
|
2015-10-10 03:40:36 +08:00
|
|
|
@_timeoutId = null
|
|
|
|
|
|
|
|
start: ->
|
|
|
|
# Clear any scheduled actions
|
|
|
|
@end()
|
|
|
|
|
|
|
|
# Look up existing data from db
|
2015-12-08 08:52:46 +08:00
|
|
|
DatabaseStore.findJSONBlob(@key).then (json) =>
|
2017-03-23 05:34:03 +08:00
|
|
|
if json? and json.refreshInterval
|
|
|
|
@refreshInterval = json.refreshInterval
|
2015-10-10 03:40:36 +08:00
|
|
|
|
|
|
|
# Refresh immediately if json is missing or version is outdated. Otherwise,
|
|
|
|
# compute next refresh time and schedule
|
|
|
|
timeUntilRefresh = 0
|
|
|
|
if json? and json.version is @version
|
|
|
|
timeUntilRefresh = Math.max(0, @refreshInterval - (Date.now() - json.time))
|
|
|
|
|
|
|
|
@_timeoutId = setTimeout(@refresh, timeUntilRefresh)
|
|
|
|
|
|
|
|
reset: ->
|
|
|
|
# Clear db value, turn off any scheduled actions
|
2015-12-18 03:46:05 +08:00
|
|
|
DatabaseStore.inTransaction (t) => t.persistJSONBlob(@key, {})
|
2015-10-10 03:40:36 +08:00
|
|
|
@end()
|
|
|
|
|
|
|
|
end: ->
|
|
|
|
# Turn off any scheduled actions
|
|
|
|
clearInterval(@_timeoutId) if @_timeoutId
|
|
|
|
@_timeoutId = null
|
|
|
|
|
|
|
|
refresh: =>
|
|
|
|
# Set up next refresh call
|
|
|
|
clearTimeout(@_timeoutId) if @_timeoutId
|
|
|
|
@_timeoutId = setTimeout(@refresh, @refreshInterval)
|
|
|
|
|
|
|
|
# Call fetch data function, save it to the database
|
|
|
|
@fetchData (newValue) =>
|
2015-12-18 03:46:05 +08:00
|
|
|
DatabaseStore.inTransaction (t) =>
|
|
|
|
t.persistJSONBlob(@key, {
|
|
|
|
version: @version
|
|
|
|
time: Date.now()
|
|
|
|
value: newValue
|
2017-03-23 05:34:03 +08:00
|
|
|
refreshInterval: @refreshInterval
|
2015-12-18 03:46:05 +08:00
|
|
|
})
|
2015-10-10 03:40:36 +08:00
|
|
|
|
|
|
|
fetchData: (callback) =>
|
|
|
|
throw new Error("Subclasses should override this method.")
|
|
|
|
|
|
|
|
|
|
|
|
|
2015-11-12 02:25:11 +08:00
|
|
|
module.exports = RefreshingJSONCache
|