Skip to content

Commit

Permalink
Adding new protocol method implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
ashlirankin committed Jan 31, 2023
1 parent 2868294 commit 4300fac
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Sources/Persister/MemoryCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ extension MemoryCache: Cache {
}

public func write<Item: Codable>(item: Item, forKey key: String) throws {
try write(item: item, forKey: key, expirationPolicy: expirationPolicy)
}

public func write<Item>(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)

Expand Down
5 changes: 5 additions & 0 deletions Sources/Persister/Persister.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ extension Persister: Cache {
try diskCache.write(item: item, forKey: key)
}

public func write<Item: Codable>(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)
Expand Down
19 changes: 19 additions & 0 deletions Tests/DiskCacheTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<TestCodable>? = try? cache.read(forKey: self.itemKey)

XCTAssertNotNil(item1)

expectation.fulfill()
}
wait(for: [expectation], timeout: 5)
}
}

0 comments on commit 4300fac

Please sign in to comment.