cache.nim 1.2 KB

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