@@ -20,15 +20,24 @@ import DependenciesMacros
2020
2121@DependencyClient
2222struct RedisClient {
23- var set : @Sendable ( _ key: String , _ value: String ? ) async -> Void
23+ var set : @Sendable ( _ key: String , _ value: String ? , Duration ? ) async -> Void
2424 var get : @Sendable ( _ key: String ) async -> String ?
2525}
2626
2727
28+ extension RedisClient {
29+ func set( key: String , value: String ? , expiresIn: Duration ? = nil ) async {
30+ await set ( key: key, value: value, expiresIn)
31+ }
32+ }
33+
34+
2835extension RedisClient : DependencyKey {
2936 static var liveValue : RedisClient {
3037 . init(
31- set: { key, value in await Redis . shared? . set ( key: key, value: value) } ,
38+ set: { key, value, expiresIn in
39+ await Redis . shared? . set ( key: key, value: value, expiresIn: expiresIn)
40+ } ,
3241 get: { key in await Redis . shared? . get ( key: key) }
3342 )
3443 }
@@ -51,7 +60,7 @@ extension DependencyValues {
5160#if DEBUG
5261extension RedisClient {
5362 static var disabled : Self {
54- . init( set: { _, _ in } , get: { _ in nil } )
63+ . init( set: { _, _, _ in } , get: { _ in nil } )
5564 }
5665}
5766#endif
@@ -92,17 +101,19 @@ private actor Redis {
92101 self . client = try await connection. get ( )
93102 }
94103
95- #warning("move expiry to interface")
96- static let expirationInSeconds = 5 * 60
97104 static let hostname = " redis "
98105 static let maxConnectionAttempts = 3
99106
100- func set( key: String , value: String ? ) async -> Void {
107+ func set( key: String , value: String ? , expiresIn : Duration ? ) async -> Void {
101108 if let value {
102109 let buffer = ByteBuffer ( string: value)
103- try ? await client. setex ( . init( key) ,
104- to: RESPValue . bulkString ( buffer) ,
105- expirationInSeconds: Self . expirationInSeconds) . get ( )
110+ let value = RESPValue . bulkString ( buffer)
111+ if let expiresIn {
112+ let ttl = Int ( expiresIn. components. seconds)
113+ try ? await client. setex ( . init( key) , to: value, expirationInSeconds: ttl) . get ( )
114+ } else {
115+ try ? await client. set ( . init( key) , to: value) . get ( )
116+ }
106117 } else {
107118 _ = try ? await client. delete ( [ . init( key) ] ) . get ( )
108119 }
0 commit comments