StorageAware.swift 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import Foundation
  2. /// A protocol used for saving and loading from storage
  3. public protocol StorageAware {
  4. associatedtype T
  5. /**
  6. Tries to retrieve the object from the storage.
  7. - Parameter key: Unique key to identify the object in the cache
  8. - Returns: Cached object or nil if not found
  9. */
  10. func object(forKey key: String) throws -> T
  11. /**
  12. Get cache entry which includes object with metadata.
  13. - Parameter key: Unique key to identify the object in the cache
  14. - Returns: Object wrapper with metadata or nil if not found
  15. */
  16. func entry(forKey key: String) throws -> Entry<T>
  17. /**
  18. Removes the object by the given key.
  19. - Parameter key: Unique key to identify the object.
  20. */
  21. func removeObject(forKey key: String) throws
  22. /**
  23. Saves passed object.
  24. - Parameter key: Unique key to identify the object in the cache.
  25. - Parameter object: Object that needs to be cached.
  26. - Parameter expiry: Overwrite expiry for this object only.
  27. */
  28. func setObject(_ object: T, forKey key: String, expiry: Expiry?) throws
  29. /**
  30. Check if an object exist by the given key.
  31. - Parameter key: Unique key to identify the object.
  32. */
  33. func existsObject(forKey key: String) throws -> Bool
  34. /**
  35. Removes all objects from the cache storage.
  36. */
  37. func removeAll() throws
  38. /**
  39. Clears all expired objects.
  40. */
  41. func removeExpiredObjects() throws
  42. /**
  43. Check if an expired object by the given key.
  44. - Parameter key: Unique key to identify the object.
  45. */
  46. func isExpiredObject(forKey key: String) throws -> Bool
  47. }
  48. public extension StorageAware {
  49. func object(forKey key: String) throws -> T {
  50. return try entry(forKey: key).object
  51. }
  52. func existsObject(forKey key: String) throws -> Bool {
  53. do {
  54. let _: T = try object(forKey: key)
  55. return true
  56. } catch {
  57. return false
  58. }
  59. }
  60. func isExpiredObject(forKey key: String) throws -> Bool {
  61. do {
  62. let entry = try self.entry(forKey: key)
  63. return entry.expiry.isExpired
  64. } catch {
  65. return true
  66. }
  67. }
  68. }