Skip to content

Instantly share code, notes, and snippets.

@vzsg
Created June 12, 2019 12:06
Show Gist options
  • Save vzsg/b3812754e46ceea869ffc3816405e26f to your computer and use it in GitHub Desktop.
Save vzsg/b3812754e46ceea869ffc3816405e26f to your computer and use it in GitHub Desktop.
MongoKitten5 Todo example
import Vapor
import MongoKitten
/// A single entry of a Todo list.
final class Todo: Content {
/// The unique identifier for this `Todo`.
var id: ObjectId?
/// A title describing what this `Todo` entails.
var title: String
/// Creates a new `Todo`.
init(id: ObjectId? = nil, title: String) {
self.id = id
self.title = title
}
private enum CodingKeys: String, CodingKey {
case id = "_id"
case title
}
}
import Vapor
import MongoKitten
/// Controls basic CRUD operations on `Todo`s.
final class TodoController {
private let collection: MongoKitten.Collection
init(mongo: MongoKitten.Database) {
self.collection = mongo["todos"]
}
/// Returns a list of all `Todo`s.
func index(_ req: Request) throws -> Future<[Todo]> {
return collection.find()
.decode(Todo.self)
.getAllResults()
}
/// Saves a decoded `Todo` to the database.
func create(_ req: Request) throws -> Future<Todo> {
return try req.content.decode(Todo.self).flatMap { todo in
todo.id = todo.id ?? ObjectId()
let encoder = BSONEncoder()
let document = try encoder.encode(todo)
return self.collection.insert(document)
.transform(to: todo)
}
}
/// Deletes a parameterized `Todo`.
func delete(_ req: Request) throws -> Future<HTTPStatus> {
let id = try req.parameters.next(String.self)
guard let oid = try? ObjectId(id) else {
throw Abort(.badRequest)
}
return collection.deleteOne(where: "_id" == oid)
.transform(to: .ok)
}
}
import Vapor
import MongoKitten
/// Called before your application initializes.
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
// Register routes to the router
services.register(Router.self) { container -> EngineRouter in
let router = EngineRouter.default()
try routes(router, container: container)
return router
}
// Register middleware
var middlewares = MiddlewareConfig() // Create _empty_ middleware config
// middlewares.use(FileMiddleware.self) // Serves files from `Public/` directory
middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response
services.register(middlewares)
let connectionURI = "mongodb://localhost/test"
services.register { container -> MongoKitten.Database in
return try MongoKitten.Database.lazyConnect(connectionURI, on: container.eventLoop)
}
}
extension MongoKitten.Database: Service {
}
import Vapor
/// Register your application's routes here.
public func routes(_ router: Router, container: Container) throws {
// Example of configuring a controller
let todoController = TodoController(mongo: try container.make())
router.get("todos", use: todoController.index)
router.post("todos", use: todoController.create)
router.delete("todos", String.parameter, use: todoController.delete)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment