Mailspring/packages/client-app/internal_packages/contact-rankings/lib/refreshing-json-cache.coffee
Mark Hahnenberg 60e6113f87 [client-sync] Implement the /contacts/rankings endpoint
Summary:
Prior to Nylas Mail, the Nylas Cloud API provided an endpoint that
returned rankings for contacts which it computed based on how frequently
and how recently a user sent mail to a recipient. This diff reimplements
that functionality in Nylas Mail. This should improve contact
auto-complete when composing emails to frequently contacted recipients.

Test Plan: Run locally, verify that frequent contacts are suggested earlier

Reviewers: spang, evan, juan

Reviewed By: evan, juan

Maniphest Tasks: T7948

Differential Revision: https://phab.nylas.com/D4253
2017-03-28 10:51:24 -07:00

57 lines
1.6 KiB
CoffeeScript

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