first commit

This commit is contained in:
Michael Simard
2020-05-25 20:58:43 -05:00
commit ba9bfd5e6a
13 changed files with 282 additions and 0 deletions

View File

View File

@@ -0,0 +1,29 @@
import Fluent
import Vapor
struct TodoController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
let todos = routes.grouped("todos")
todos.get(use: index)
todos.post(use: create)
todos.group(":todoID") { todo in
todo.delete(use: delete)
}
}
func index(req: Request) throws -> EventLoopFuture<[Todo]> {
return Todo.query(on: req.db).all()
}
func create(req: Request) throws -> EventLoopFuture<Todo> {
let todo = try req.content.decode(Todo.self)
return todo.save(on: req.db).map { todo }
}
func delete(req: Request) throws -> EventLoopFuture<HTTPStatus> {
return Todo.find(req.parameters.get("todoID"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { $0.delete(on: req.db) }
.transform(to: .ok)
}
}

View File

@@ -0,0 +1,14 @@
import Fluent
struct CreateTodo: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
return database.schema("todos")
.id()
.field("title", .string, .required)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
return database.schema("todos").delete()
}
}

View File

@@ -0,0 +1,19 @@
import Fluent
import Vapor
final class Todo: Model, Content {
static let schema = "todos"
@ID(key: .id)
var id: UUID?
@Field(key: "title")
var title: String
init() { }
init(id: UUID? = nil, title: String) {
self.id = id
self.title = title
}
}

View File

@@ -0,0 +1,21 @@
import Fluent
import FluentPostgresDriver
import Vapor
// configures your application
public func configure(_ app: Application) throws {
// uncomment to serve files from /Public folder
// app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
app.databases.use(.postgres(
hostname: Environment.get("DATABASE_HOST") ?? "localhost",
username: Environment.get("DATABASE_USERNAME") ?? "vapor_username",
password: Environment.get("DATABASE_PASSWORD") ?? "vapor_password",
database: Environment.get("DATABASE_NAME") ?? "vapor_database"
), as: .psql)
app.migrations.add(CreateTodo())
// register routes
try routes(app)
}

14
Sources/App/routes.swift Normal file
View File

@@ -0,0 +1,14 @@
import Fluent
import Vapor
func routes(_ app: Application) throws {
app.get { req in
return "It works!"
}
app.get("hello") { req -> String in
return "Hello, world!"
}
try app.register(collection: TodoController())
}