Skip to content

Instantly share code, notes, and snippets.

@emarashliev
Last active December 22, 2018 13:44
Show Gist options
  • Save emarashliev/f4a7a381958cedd554fb71b76c8e1d54 to your computer and use it in GitHub Desktop.
Save emarashliev/f4a7a381958cedd554fb71b76c8e1d54 to your computer and use it in GitHub Desktop.
Repository Case 2
// 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