forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresData+JSON.swift
56 lines (47 loc) · 1.46 KB
/
PostgresData+JSON.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
import Foundation
extension PostgresData {
public init(json jsonData: Data) {
let jsonData = [UInt8](jsonData)
var buffer = ByteBufferAllocator()
.buffer(capacity: jsonData.count)
buffer.writeBytes(jsonData)
self.init(type: .json, formatCode: .binary, value: buffer)
}
public init<T>(json value: T) throws where T: Encodable {
let jsonData = try JSONEncoder().encode(value)
self.init(json: jsonData)
}
public var json: Data? {
guard var value = self.value else {
return nil
}
guard case .json = self.type else {
return nil
}
guard let data = value.readBytes(length: value.readableBytes) else {
return nil
}
return Data(data)
}
public func json<T>(as type: T.Type) throws -> T? where T: Decodable {
guard let data = self.json else {
return nil
}
return try JSONDecoder().decode(T.self, from: data)
}
}
public protocol PostgresJSONCodable: Codable, PostgresDataConvertible { }
extension PostgresJSONCodable {
public static var postgresDataType: PostgresDataType {
return .json
}
public var postgresData: PostgresData? {
return try? .init(json: self)
}
public init?(postgresData: PostgresData) {
guard let value = try? postgresData.json(as: Self.self) else {
return nil
}
self = value
}
}