Skip to content

Commit

Permalink
support encoding arrays other than json (#172)
Browse files Browse the repository at this point in the history
* support encoding arrays other than json

* simplify decoder method

* test fluent on 5.2
  • Loading branch information
tanner0101 authored Feb 20, 2020
1 parent 222dcf7 commit 902eb00
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 14 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
- run: swift test --enable-test-discovery --sanitize=thread
fluent:
container:
image: vapor/swift:5.1
image: vapor/swift:5.2
services:
psql:
image: postgres
Expand Down
11 changes: 1 addition & 10 deletions Sources/PostgresKit/PostgresDataDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ public final class PostgresDataDecoder {
}

func unkeyedContainer() throws -> UnkeyedDecodingContainer {
print(self.data.type)
guard let data = self.data.array else {
throw Error.unexpectedDataType(self.data.type, expected: "array")
}
Expand Down Expand Up @@ -108,15 +107,7 @@ public final class PostgresDataDecoder {
mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
defer { self.currentIndex += 1 }
let data = self.data[self.currentIndex]
let jsonData: Data
if let jsonb = data.jsonb {
jsonData = jsonb
} else if let json = data.json {
jsonData = json
} else {
throw Error.unexpectedDataType(data.type, expected: "json")
}
return try self.json.decode(T.self, from: jsonData)
return try PostgresDataDecoder(json: self.json).decode(T.self, from: data)
}

mutating func nestedContainer<NestedKey>(
Expand Down
8 changes: 5 additions & 3 deletions Sources/PostgresKit/PostgresDataEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ public final class PostgresDataEncoder {
}

public func encode(_ value: Encodable) throws -> PostgresData {
if let custom = value as? PostgresDataConvertible {
return custom.postgresData!
if let custom = value as? PostgresDataConvertible, let data = custom.postgresData {
return data
} else {
let context = _Context()
try value.encode(to: _Encoder(context: context))
if let value = context.value {
return value
} else if let array = context.array {
return PostgresData(array: array, elementType: .jsonb)
let elementType = array.first?.type ?? .jsonb
assert(array.filter { $0.type != elementType }.isEmpty, "Array does not contain all: \(elementType)")
return PostgresData(array: array, elementType: elementType)
} else {
return try PostgresData(jsonb: self.json.encode(_Wrapper(value)))
}
Expand Down

0 comments on commit 902eb00

Please sign in to comment.