forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresData+JSONB.swift
67 lines (52 loc) · 1.81 KB
/
PostgresData+JSONB.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import Foundation
fileprivate let jsonBVersionBytes: [UInt8] = [0x01]
extension PostgresData {
public init(jsonb jsonData: Data) {
let jsonBData = [UInt8](jsonData)
var buffer = ByteBufferAllocator()
.buffer(capacity: jsonBVersionBytes.count + jsonBData.count)
buffer.writeBytes(jsonBVersionBytes)
buffer.writeBytes(jsonBData)
self.init(type: .jsonb, formatCode: .binary, value: buffer)
}
public init<T>(jsonb value: T) throws where T: Encodable {
let jsonData = try PostgresNIO._defaultJSONEncoder.encode(value)
self.init(jsonb: jsonData)
}
public var jsonb: Data? {
guard var value = self.value else {
return nil
}
guard case .jsonb = self.type else {
return nil
}
guard let versionBytes = value.readBytes(length: jsonBVersionBytes.count), [UInt8](versionBytes) == jsonBVersionBytes else {
return nil
}
guard let data = value.readBytes(length: value.readableBytes) else {
return nil
}
return Data(data)
}
public func jsonb<T>(as type: T.Type) throws -> T? where T: Decodable {
guard let data = jsonb else {
return nil
}
return try PostgresNIO._defaultJSONDecoder.decode(T.self, from: data)
}
}
public protocol PostgresJSONBCodable: Codable, PostgresDataConvertible { }
extension PostgresJSONBCodable {
public static var postgresDataType: PostgresDataType {
return .jsonb
}
public var postgresData: PostgresData? {
return try? .init(jsonb: self)
}
public init?(postgresData: PostgresData) {
guard let value = try? postgresData.jsonb(as: Self.self) else {
return nil
}
self = value
}
}