-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathRedisClient+Codable.swift
35 lines (32 loc) · 1.14 KB
/
RedisClient+Codable.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import AsyncKit
import Foundation
extension RedisClient {
/// Gets the provided key as a decodable type.
public func get<D>(_ key: RedisKey, asJSON type: D.Type) -> EventLoopFuture<D?>
where D: Decodable
{
return self.get(key, as: Data.self).flatMapThrowing { data in
return try data.flatMap { try JSONDecoder().decode(D.self, from: $0) }
}
}
/// Sets key to an encodable item.
public func set<E>(_ key: RedisKey, toJSON entity: E) -> EventLoopFuture<Void>
where E: Encodable
{
do {
return try self.set(key, to: JSONEncoder().encode(entity))
} catch {
return self.eventLoop.makeFailedFuture(error)
}
}
/// Sets key to an encodable item with an expiration time.
public func setex<E>(_ key: RedisKey, toJSON entity: E, expirationInSeconds expiration: Int) -> EventLoopFuture<Void>
where E: Encodable
{
do {
return try self.setex(key, to: JSONEncoder().encode(entity), expirationInSeconds: expiration)
} catch {
return self.eventLoop.makeFailedFuture(error)
}
}
}