Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MihaelIsaev/43d70070d7481064bc722556108a9521 to your computer and use it in GitHub Desktop.
Save MihaelIsaev/43d70070d7481064bc722556108a9521 to your computer and use it in GitHub Desktop.
Vapor3 PostgreSQL extension to decode [[PostgreSQLColumn: PostgreSQLData]] with Codable struct
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