diff --git a/Sources/Persister/MemoryCache.swift b/Sources/Persister/MemoryCache.swift index a64acf6..fae77ef 100644 --- a/Sources/Persister/MemoryCache.swift +++ b/Sources/Persister/MemoryCache.swift @@ -38,6 +38,10 @@ extension MemoryCache: Cache { } public func write(item: Item, forKey key: String) throws { + try write(item: item, forKey: key, expirationPolicy: expirationPolicy) + } + + public func write(item: Item, forKey key: String, expirationPolicy: CacheExpirationPolicy) throws where Item : Decodable, Item : Encodable { let expirationDate = expirationPolicy.expirationDate(from: Date()) let container = ItemContainer(item: item, expirationDate: expirationDate) diff --git a/Sources/Persister/Persister.swift b/Sources/Persister/Persister.swift index 3a7f4e3..7738a70 100644 --- a/Sources/Persister/Persister.swift +++ b/Sources/Persister/Persister.swift @@ -48,6 +48,11 @@ extension Persister: Cache { try diskCache.write(item: item, forKey: key) } + public func write(item: Item, forKey key: String, expirationPolicy: CacheExpirationPolicy) throws { + try memoryCache.write(item: item, forKey: key, expirationPolicy: expirationPolicy) + try diskCache.write(item: item, forKey: key, expirationPolicy: expirationPolicy) + } + public func remove(forKey key: String) throws { try memoryCache.remove(forKey: key) try diskCache.remove(forKey: key) diff --git a/Tests/DiskCacheTests.swift b/Tests/DiskCacheTests.swift index 55f10ae..96e76cb 100644 --- a/Tests/DiskCacheTests.swift +++ b/Tests/DiskCacheTests.swift @@ -91,4 +91,23 @@ final class DiskCacheTests: XCTestCase { } } } + + func testUsesCorrectExpirationPolicy() throws { + let expectation = XCTestExpectation(description: "Only one item should have been removed.") + + let cache = DiskCache(rootDirectoryURL: diskURL, expirationPolicy: .afterInterval(1)) + try cache.write(item: TestCodable(), forKey: itemKey, expirationPolicy: .afterInterval(500)) + + DispatchQueue.main.asyncAfter(deadline: .now() + 2) { + + try? cache.removeExpired() + + let item1: ItemContainer? = try? cache.read(forKey: self.itemKey) + + XCTAssertNotNil(item1) + + expectation.fulfill() + } + wait(for: [expectation], timeout: 5) + } }