Flatiron Labs
Published in

Flatiron Labs

Persisting Data with Vapor 3 and PostgreSQL

A server-side Swift tutorial

vapor --version
Click on foodtracker-Package
.package(url: "https://github.com/vapor/fluent-postgresql.git", from: "1.0.0")
try services.register(FluentPostgreSQLProvider())
let config = PostgreSQLDatabaseConfig(hostname: "localhost", port: 5432, username: "jkerr", database: "foodtracker", password: nil, transport: .cleartext)let postgres = PostgreSQLDatabase(config: config)
databases.add(database: postgres, as: .psql)
import Foundation
import FluentPostgreSQL
final class Meal: PostgreSQLModel {
var id: Int?
}
final class Meal: PostgreSQLModel {
var id: Int?
var description: String

init(description: String) {
self.description = description
}
}
// Allows `Meal` to be used as a dynamic migration.
extension Meal: Migration { }
/// Allows `Todo` to be encoded to and decoded from HTTP messages.
extension Meal: Content { }
/// Allows `Meal` to be used as a dynamic parameter in route definitions.
extension Meal: Parameter { }
migrations.add(model: Meal.self, database: .psql)
import Foundation
import Vapor
final class MealController {
func index(_ req: Request) throws -> Future<[Meal]> {
return Meal.query(on: req).all()
}

func create(_ req: Request) throws -> Future<Meal> {
return try req.content.decode(Meal.self).flatMap { meal in
return meal.save(on: req)
}
}
}
Meal.query(on: req).all()
let mealController = MealController()
router.get("meals", use: mealController.index)
router.post("meals", use: mealController.create)

--

--

We're the technology team at The Flatiron School (a WeWork company). Together, we're building a global campus for lifelong learners focused on positive impact.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Johann Kerr

Software Engineer @FlatironSchool, formerly Lead iOS & Web Instructor at //