Mailspring/packages/client-app/internal_packages/contact-rankings/lib/refreshing-json-cache.coffee
Juan Tejada da463c250f [client-app] Consolidate delta connection stores, rm deltas internal_pkg
Summary:
This commit consolidates the `DeltaConnectionStatusStore` and the
`DeltaConnectionStore` which kept track of very similar state and made
sense to be the same store (as per feedback in D4118#77647)

Given that this state needs to be available app-wide for plugins to
query the status of delta connections, `internal_packages/deltas` was
removed (given that it only activated that store), in favor of having the
unified store inside `src/flux/stores` and available via `nylas-exports`

The `deltas` package also contained some contacts-ranking code, which is
no longer in use until we restore that fetaure, so I created a
`internal_packages/contact-rankings` which contains this unused code for
now.

Test Plan:
manually open, close, end delta connections, verify that I'm getting
correct results. unit tests to come

Reviewers: halla, spang, evan

Reviewed By: evan

Differential Revision: https://phab.nylas.com/D4145
2017-03-09 15:27:06 -08:00

55 lines
1.4 KiB
CoffeeScript

_ = require 'underscore'
{NylasStore, DatabaseStore} = require 'nylas-exports'
class RefreshingJSONCache
constructor: ({@key, @version, @refreshInterval}) ->
@_timeoutId = null
start: ->
# Clear any scheduled actions
@end()
# Look up existing data from db
DatabaseStore.findJSONBlob(@key).then (json) =>
# 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
DatabaseStore.inTransaction (t) => t.persistJSONBlob(@key, {})
@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) =>
DatabaseStore.inTransaction (t) =>
t.persistJSONBlob(@key, {
version: @version
time: Date.now()
value: newValue
})
fetchData: (callback) =>
throw new Error("Subclasses should override this method.")
module.exports = RefreshingJSONCache