Skip to content

Commit 096014c

Browse files
author
Lug4rd
committed
Extend storage aware protocol
Added check function for expired object by key
1 parent ed4f5ca commit 096014c

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

Source/Shared/Storage/StorageAware.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,12 @@ public protocol StorageAware {
4545
Clears all expired objects.
4646
*/
4747
func removeExpiredObjects() throws
48+
49+
/**
50+
Check if an expired object by the given key.
51+
- Parameter key: Unique key to identify the object.
52+
*/
53+
func isExpiredObject<T: Codable>(ofType type: T.Type, forKey key: String) throws -> Bool
4854
}
4955

5056
public extension StorageAware {
@@ -60,4 +66,13 @@ public extension StorageAware {
6066
return false
6167
}
6268
}
69+
70+
func isExpiredObject<T: Codable>(ofType type: T.Type, forKey key: String) throws -> Bool {
71+
do {
72+
let entry = try self.entry(ofType: type, forKey: key)
73+
return entry.expiry.isExpired
74+
} catch {
75+
return true
76+
}
77+
}
6378
}

Tests/iOS/Tests/Storage/DiskStorageTests.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,14 @@ final class DiskStorageTests: XCTestCase {
129129
let cachedObject: User? = try storage.object(ofType: User.self, forKey: key)
130130
XCTAssertNotNil(cachedObject)
131131
}
132+
133+
/// Test expired object
134+
func testExpiredObject() throws {
135+
try storage.setObject(testObject, forKey: key, expiry: .seconds(0.9))
136+
XCTAssertFalse(try! storage.isExpiredObject(ofType: User.self, forKey: key))
137+
sleep(1)
138+
XCTAssertTrue(try! storage.isExpiredObject(ofType: User.self, forKey: key))
139+
}
132140

133141
/// Test that it clears cache directory
134142
func testClear() throws {

Tests/iOS/Tests/Storage/MemoryStorageTests.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,14 @@ final class MemoryStorageTests: XCTestCase {
8181

8282
XCTAssertNotNil(cachedObject)
8383
}
84+
85+
/// Test expired object
86+
func testExpiredObject() throws {
87+
storage.setObject(testObject, forKey: key, expiry: .seconds(0.9))
88+
XCTAssertFalse(try! storage.isExpiredObject(ofType: User.self, forKey: key))
89+
sleep(1)
90+
XCTAssertTrue(try! storage.isExpiredObject(ofType: User.self, forKey: key))
91+
}
8492

8593
/// Test that it clears cache directory
8694
func testRemoveAll() {

0 commit comments

Comments
 (0)