Skip to content

Instantly share code, notes, and snippets.

@29satnam
Created February 15, 2019 12:42
Show Gist options
  • Save 29satnam/a12ce5c131b879c001abe813b7c89f65 to your computer and use it in GitHub Desktop.
Save 29satnam/a12ce5c131b879c001abe813b7c89f65 to your computer and use it in GitHub Desktop.
Basic CRUD with Vapor - Swift
import Vapor
/// Register your application's routes here.
public func routes(_ router: Router) throws {
// Saving models
router.post("api", "acronyms") { req -> Future<Acronym> in
return try req.content.decode(Acronym.self)
.flatMap(to: Acronym.self) { acronym in
return acronym.save(on: req)
}
}
// Retrieve all acronyms
router.get("api", "acronyms") { (req) -> Future<[Acronym]> in
return Acronym.query(on: req).all()
}
// Retrieve a single acronym
router.get("api", "acronyms", Acronym.parameter) {
req -> Future<Acronym> in
return try req.parameters.next(Acronym.self)
}
// Update
router.put("api", "acronyms", Acronym.parameter) {
req -> Future<Acronym> in
// Use flatMap(to:_:_:), the dual future form of flatMap, to wait for both the parameter extraction and content decoding to complete. This provides both the acronym from the database and acronym from the request body to the closure.
return try flatMap(to: Acronym.self, req.parameters.next(Acronym.self), req.content.decode(Acronym.self)) {
acronym, updatedAcronym in
acronym.short = updatedAcronym.short
acronym.long = updatedAcronym.long
return acronym.save(on: req)
}
}
// Delete
router.delete("api", "acronyms", Acronym.parameter) { req -> Future<HTTPStatus> in
return try req.parameters.next(Acronym.self).delete(on: req).transform(to: HTTPStatus.noContent)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment