cache.nim 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. safeAddColumn Profile.lowername
  16. var profileCacheTime = initDuration(minutes=10)
  17. proc isOutdated*(profile: Profile): bool =
  18. getTime() - profile.updated > profileCacheTime
  19. proc cache*(profile: var Profile) =
  20. withDb:
  21. try:
  22. let p = Profile.getOne("lowername = ?", profile.lowername)
  23. profile.id = p.id
  24. profile.update()
  25. except KeyError:
  26. if profile.username.len > 0:
  27. profile.insert()
  28. proc hasCachedProfile*(username: string): Option[Profile] =
  29. withDb:
  30. try:
  31. let p = Profile.getOne("lowername = ?", toLower(username))
  32. doAssert not p.isOutdated
  33. result = some p
  34. except AssertionError, KeyError:
  35. result = none Profile
  36. proc getCachedProfile*(username, agent: string;
  37. force=false): Future[Profile] {.async.} =
  38. withDb:
  39. try:
  40. result.getOne("lowername = ?", toLower(username))
  41. doAssert not result.isOutdated
  42. except AssertionError, KeyError:
  43. result = await getProfileFull(username, agent)
  44. cache(result)
  45. proc setProfileCacheTime*(minutes: int) =
  46. profileCacheTime = initDuration(minutes=minutes)
  47. proc cache*(video: var Video) =
  48. withDb:
  49. try:
  50. let v = Video.getOne("videoId = ?", video.videoId)
  51. video.id = v.id
  52. video.update()
  53. except KeyError:
  54. if video.videoId.len > 0:
  55. video.insert()
  56. proc uncache*(id: int64) =
  57. withDb:
  58. try:
  59. var video = Video.getOne("videoId = ?", $id)
  60. video.delete()
  61. except:
  62. discard
  63. proc getCachedVideo*(id: int64): Option[Video] =
  64. withDb:
  65. try:
  66. return some Video.getOne("videoId = ?", $id)
  67. except KeyError:
  68. return none Video