Last active
December 22, 2018 13:44
-
-
Save emarashliev/f4a7a381958cedd554fb71b76c8e1d54 to your computer and use it in GitHub Desktop.
Repository Case 2
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
// The Model | |
final class User<D>: Model where D: Database & QuerySupporting { | |
typealias Database = D | |
typealias ID = Int | |
static var idKey: IDKey { return \.id } | |
var id: Int? | |
var name: String | |
var email: String | |
} | |
// The Repository | |
protocol UserRepository: ServiceType { | |
associatedtype D: QuerySupporting | |
func all() -> Future<[User<D>]> | |
} | |
final class MySQLUserRepository: UserRepository { | |
typealias D = MySQLDatabase | |
let db: MySQLDatabase.ConnectionPool | |
init(_ db: MySQLDatabase.ConnectionPool) { | |
self.db = db | |
} | |
func all() -> Future<[User<D>]> { | |
return db.withConnection { conn in | |
return User.query(on: conn).all() | |
} | |
} | |
} | |
// The Controller | |
struct UsersController { /// 👇 this | |
func getAllHandler(_ req: Request) throws -> Future<[User<MySQLMovieRepository.D>>]> { | |
/// and this👇 | |
let repository = try req.make(MySQLMovieRepository.self) | |
return repository.all() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment