cache.nim 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import asyncdispatch, times, strutils
  2. import norm/sqlite
  3. import types, api/profile
  4. template safeAddColumn(field: typedesc): untyped =
  5. try: field.addColumn
  6. except DbError: discard
  7. dbFromTypes("cache.db", "", "", "", [Profile, Video])
  8. withDb:
  9. try:
  10. createTables()
  11. except DbError:
  12. discard
  13. Video.title.safeAddColumn
  14. Video.description.safeAddColumn
  15. var profileCacheTime = initDuration(minutes=10)
  16. proc isOutdated*(profile: Profile): bool =
  17. getTime() - profile.updated > profileCacheTime
  18. proc cache*(profile: var Profile) =
  19. withDb:
  20. try:
  21. let p = Profile.getOne("lower(username) = ?", toLower(profile.username))
  22. profile.id = p.id
  23. profile.update()
  24. except KeyError:
  25. if profile.username.len > 0:
  26. profile.insert()
  27. proc hasCachedProfile*(username: string): Option[Profile] =
  28. withDb:
  29. try:
  30. let p = Profile.getOne("lower(username) = ?", toLower(username))
  31. doAssert not p.isOutdated
  32. result = some p
  33. except AssertionError, KeyError:
  34. result = none Profile
  35. proc getCachedProfile*(username, agent: string; force=false): Future[Profile] {.async.} =
  36. withDb:
  37. try:
  38. result.getOne("lower(username) = ?", toLower(username))
  39. doAssert not result.isOutdated
  40. except AssertionError, KeyError:
  41. result = await getProfileFull(username, agent)
  42. cache(result)
  43. proc setProfileCacheTime*(minutes: int) =
  44. profileCacheTime = initDuration(minutes=minutes)
  45. proc cache*(video: var Video) =
  46. withDb:
  47. try:
  48. let v = Video.getOne("videoId = ?", video.videoId)
  49. video.id = v.id
  50. video.update()
  51. except KeyError:
  52. if video.videoId.len > 0:
  53. video.insert()
  54. proc getCachedVideo*(id: int): Option[Video] =
  55. withDb:
  56. try:
  57. return some Video.getOne("videoId = ?", $id)
  58. except KeyError:
  59. return none Video