Created
May 29, 2018 01:13
-
-
Save MihaelIsaev/43d70070d7481064bc722556108a9521 to your computer and use it in GitHub Desktop.
Vapor3 PostgreSQL extension to decode [[PostgreSQLColumn: PostgreSQLData]] with Codable struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PostgreSQL | |
typealias PostgreSQLQueryRow = [PostgreSQLColumn: PostgreSQLData] | |
extension Dictionary where Key == PostgreSQLColumn, Value == PostgreSQLData { | |
func decode<T>(_ key: String) throws -> T where T: PostgreSQLDataConvertible { | |
guard let v = try firstValue(forColumn: key)?.decode(T.self) else { | |
throw PostgreSQLError(identifier: "decodingError", reason: "Unable to decode \"\(key)\" column ", source: .capture()) | |
} | |
return v | |
} | |
} | |
//Example usage | |
struct User: Content { | |
var id: UUID | |
var name: String | |
var email: String | |
init (_ queryData: PostgreSQLQueryRow) throws { | |
id = try queryData.decode( "id") | |
name = try queryData.decode("name") | |
email = try queryData.decode("email") | |
} | |
} | |
func someEndpoint(_ req: Request) throws -> Future<[User]> { | |
return req.requestPooledConnection(to: .psql).flatMap { conn -> EventLoopFuture<[User]> in | |
return conn.query("SELECT id, name, email FROM \"Users\"").map { queryResult -> [User] in | |
return try queryResult.map { try User($0) } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment