File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
Modules/Sources/WordPressCore/DataStore Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ import Foundation
2+
3+ public actor DiskCache {
4+
5+ struct Wrapper < T> : Codable where T: Codable {
6+ let date : Date
7+ let data : T
8+ }
9+
10+ public func store< T> ( object: T , for key: String ) throws where T: Codable {
11+ try self . ensureCacheDirectoryExists ( )
12+
13+ let wrapper = Wrapper ( date: Date ( ) , data: object)
14+ let data = try JSONEncoder ( ) . encode ( wrapper)
15+
16+ FileManager . default. createFile ( atPath: self . cacheURL ( for: key) . path ( ) , contents: data)
17+ }
18+
19+ public func retrieve< T> ( for key: String , notOlderThan date: Date ? = nil ) throws -> T ? where T: Codable {
20+ try self . ensureCacheDirectoryExists ( )
21+
22+ let path = self . cacheURL ( for: key)
23+ guard FileManager . default. fileExists ( at: path) else {
24+ return nil
25+ }
26+
27+ let data = try Data ( contentsOf: path)
28+ let wrapper = try JSONDecoder ( ) . decode ( Wrapper< T> . self , from: data)
29+
30+ if let date {
31+ if wrapper. date > date {
32+ return nil
33+ }
34+ }
35+
36+ return wrapper. data
37+ }
38+
39+ private func ensureCacheDirectoryExists( ) throws {
40+ try FileManager . default. createDirectory (
41+ at: cacheURL ( for: " " ) . deletingLastPathComponent ( ) ,
42+ withIntermediateDirectories: true
43+ )
44+ }
45+
46+ private func cacheURL( for key: String ) -> URL {
47+ URL . cachesDirectory
48+ . appendingPathComponent ( " object-cache " )
49+ . appendingPathComponent ( key)
50+ . appendingPathExtension ( " json " )
51+ }
52+ }
You can’t perform that action at this time.
0 commit comments