nitter/src/cache.nim

66 lines
1.6 KiB
Nim
Raw Normal View History

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