forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSON+PSQLCodable.swift
35 lines (30 loc) · 1.29 KB
/
JSON+PSQLCodable.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 NIOCore
import NIOFoundationCompat
import class Foundation.JSONEncoder
import class Foundation.JSONDecoder
private let JSONBVersionByte: UInt8 = 0x01
extension PSQLCodable where Self: Codable {
var psqlType: PSQLDataType {
.jsonb
}
var psqlFormat: PSQLFormat {
.binary
}
static func decode(from buffer: inout ByteBuffer, type: PSQLDataType, format: PSQLFormat, context: PSQLDecodingContext) throws -> Self {
switch (format, type) {
case (.binary, .jsonb):
guard JSONBVersionByte == buffer.readInteger(as: UInt8.self) else {
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
return try context.jsonDecoder.decode(Self.self, from: buffer)
case (.binary, .json), (.text, .jsonb), (.text, .json):
return try context.jsonDecoder.decode(Self.self, from: buffer)
default:
throw PSQLCastingError.failure(targetType: Self.self, type: type, postgresData: buffer, context: context)
}
}
func encode(into byteBuffer: inout ByteBuffer, context: PSQLEncodingContext) throws {
byteBuffer.writeInteger(JSONBVersionByte)
try context.jsonEncoder.encode(self, into: &byteBuffer)
}
}