nitter/src/cache.nim

47 lines
1.2 KiB
Nim
Raw Normal View History

2019-09-08 10:22:52 +00:00
import asyncdispatch, times, strutils
2019-06-20 14:16:20 +00:00
import types, api
2019-09-08 10:22:52 +00:00
dbFromTypes("cache.db", "", "", "", [Profile, Video])
withDb:
2019-06-20 18:04:18 +00:00
try:
createTables()
except DbError:
discard
2019-06-24 23:00:23 +00:00
var profileCacheTime = initDuration(minutes=10)
2019-06-20 18:04:18 +00:00
proc isOutdated*(profile: Profile): bool =
2019-06-20 18:04:18 +00:00
getTime() - profile.updated > profileCacheTime
proc cache*(profile: var Profile) =
2019-09-08 10:22:52 +00:00
withDb:
2019-06-20 18:04:18 +00:00
try:
let p = Profile.getOne("lower(username) = ?", toLower(profile.username))
profile.id = p.id
profile.update()
2019-06-24 22:55:41 +00:00
except KeyError:
if profile.username.len > 0:
profile.insert()
proc hasCachedProfile*(username: string): Option[Profile] =
2019-09-08 10:22:52 +00:00
withDb:
try:
let p = Profile.getOne("lower(username) = ?", toLower(username))
doAssert not p.isOutdated
2019-09-18 18:54:07 +00:00
result = some p
except AssertionError, KeyError:
2019-09-18 18:54:07 +00:00
result = none Profile
proc getCachedProfile*(username, agent: string; force=false): Future[Profile] {.async.} =
2019-09-08 10:22:52 +00:00
withDb:
try:
result.getOne("lower(username) = ?", toLower(username))
doAssert not result.isOutdated
except AssertionError, KeyError:
2019-10-02 08:13:17 +00:00
result = await getProfileFull(username, agent)
cache(result)
2019-07-31 00:15:43 +00:00
proc setProfileCacheTime*(minutes: int) =
profileCacheTime = initDuration(minutes=minutes)