Skip to content

Instantly share code, notes, and snippets.

@jaekong
Last active April 16, 2021 15:26
Show Gist options
  • Save jaekong/152c7ac5e14be080c05671298f8cebf0 to your computer and use it in GitHub Desktop.
Save jaekong/152c7ac5e14be080c05671298f8cebf0 to your computer and use it in GitHub Desktop.
CRUD Controller protocol for Vapor 4 and Swift 5.2. It adds basic REST API for CRUD-ing any model with an UUID identifier. It is based on the default controller example, but has not been tested yet. A controller struct can conform to this protocol by adding typealias M for your Model, and adding a variable called path that determines subpath of …
import Fluent
import Vapor
protocol CRUDController: RouteCollection {
associatedtype M: Model, Content where M.IDValue == UUID
var path: [PathComponent] { get set }
init()
}
extension CRUDController {
init(path: PathComponent...) {
self.init()
self.path = path
}
func boot(routes: RoutesBuilder) throws {
let router = routes.grouped(path)
router.get(use: index)
router.post(use: create)
router.delete(":id", use: delete)
}
func index(req: Request) throws -> EventLoopFuture<[M]> {
return M.query(on: req.db).all()
}
func create(req: Request) throws -> EventLoopFuture<M> {
let entry = try req.content.decode(M.self)
return entry.save(on: req.db).map { entry }
}
func delete(req: Request) throws -> EventLoopFuture<HTTPStatus> {
return M.find(req.parameters.get("id"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { $0.delete(on: req.db) }
.transform(to: .ok)
}
}
/*
struct ExampleController: CRUDController {
typealias M = ExampleModel
var path: [PathComponent] = [] // You need to provide a default value for path, or an init().
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment