cache.nim 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import asyncdispatch, times, strutils
  2. import types, api
  3. dbFromTypes("cache.db", "", "", "", [Profile, Video])
  4. withDb:
  5. try:
  6. createTables()
  7. except DbError:
  8. discard
  9. var profileCacheTime = initDuration(minutes=10)
  10. proc isOutdated*(profile: Profile): bool =
  11. getTime() - profile.updated > profileCacheTime
  12. proc cache*(profile: var Profile) =
  13. withDb:
  14. try:
  15. let p = Profile.getOne("lower(username) = ?", toLower(profile.username))
  16. profile.id = p.id
  17. profile.update()
  18. except KeyError:
  19. if profile.username.len > 0:
  20. profile.insert()
  21. proc hasCachedProfile*(username: string): Option[Profile] =
  22. withDb:
  23. try:
  24. let p = Profile.getOne("lower(username) = ?", toLower(username))
  25. doAssert not p.isOutdated
  26. result = some p
  27. except AssertionError, KeyError:
  28. result = none Profile
  29. proc getCachedProfile*(username, agent: string; force=false): Future[Profile] {.async.} =
  30. withDb:
  31. try:
  32. result.getOne("lower(username) = ?", toLower(username))
  33. doAssert not result.isOutdated
  34. except AssertionError, KeyError:
  35. result = await getProfileFull(username, agent)
  36. cache(result)
  37. proc setProfileCacheTime*(minutes: int) =
  38. profileCacheTime = initDuration(minutes=minutes)