|
| 1 | +import Models |
| 2 | +import MongoDBVapor |
| 3 | +import Vapor |
| 4 | + |
| 5 | +// Adds API routes to the application. |
| 6 | +func routes(_ app: Application) throws { |
| 7 | + /// Handles a request to load the list of kittens. |
| 8 | + app.get { req async throws -> [Kitten] in |
| 9 | + try await req.findKittens() |
| 10 | + } |
| 11 | + |
| 12 | + /// Handles a request to add a new kitten. |
| 13 | + app.post { req async throws -> Response in |
| 14 | + try await req.addKitten() |
| 15 | + } |
| 16 | + |
| 17 | + /// Handles a request to load info about a particular kitten. |
| 18 | + app.get(":_id") { req async throws -> Kitten in |
| 19 | + try await req.findKitten() |
| 20 | + } |
| 21 | + |
| 22 | + app.delete(":_id") { req async throws -> Response in |
| 23 | + try await req.deleteKitten() |
| 24 | + } |
| 25 | + |
| 26 | + app.patch(":_id") { req async throws -> Response in |
| 27 | + try await req.updateKitten() |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/// Extend the `Kitten` model type to conform to Vapor's `Content` protocol so that it may be converted to and |
| 32 | +/// initialized from HTTP data. |
| 33 | +extension Kitten: Content {} |
| 34 | + |
| 35 | +extension Request { |
| 36 | + /// Convenience extension for obtaining a collection. |
| 37 | + var kittenCollection: MongoCollection<Kitten> { |
| 38 | + self.application.mongoDB.client.db("home").collection("kittens", withType: Kitten.self) |
| 39 | + } |
| 40 | + |
| 41 | + /// Constructs a document using the _id from this request which can be used a filter for MongoDB |
| 42 | + /// reads/updates/deletions. |
| 43 | + func getIDFilter() throws -> BSONDocument { |
| 44 | + // We only call this method from request handlers that have _id parameters so the value |
| 45 | + // should always be available. |
| 46 | + guard let idString = self.parameters.get("_id", as: String.self) else { |
| 47 | + throw Abort(.badRequest, reason: "Request missing _id for kitten") |
| 48 | + } |
| 49 | + guard let _id = try? BSONObjectID(idString) else { |
| 50 | + throw Abort(.badRequest, reason: "Invalid _id string \(idString)") |
| 51 | + } |
| 52 | + return ["_id": .objectID(_id)] |
| 53 | + } |
| 54 | + |
| 55 | + func findKittens() async throws -> [Kitten] { |
| 56 | + do { |
| 57 | + return try await self.kittenCollection.find().toArray() |
| 58 | + } catch { |
| 59 | + throw Abort(.internalServerError, reason: "Failed to load kittens: \(error)") |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + func findKitten() async throws -> Kitten { |
| 64 | + let idFilter = try self.getIDFilter() |
| 65 | + guard let kitten = try await self.kittenCollection.findOne(idFilter) else { |
| 66 | + throw Abort(.notFound, reason: "No kitten with matching _id") |
| 67 | + } |
| 68 | + return kitten |
| 69 | + } |
| 70 | + |
| 71 | + func addKitten() async throws -> Response { |
| 72 | + let newKitten = try self.content.decode(Kitten.self) |
| 73 | + do { |
| 74 | + try await self.kittenCollection.insertOne(newKitten) |
| 75 | + return Response(status: .created) |
| 76 | + } catch { |
| 77 | + throw Abort(.internalServerError, reason: "Failed to save new kitten: \(error)") |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + func deleteKitten() async throws -> Response { |
| 82 | + let idFilter = try self.getIDFilter() |
| 83 | + do { |
| 84 | + // since we aren't using an unacknowledged write concern we can expect deleteOne to return a non-nil result. |
| 85 | + guard let result = try await self.kittenCollection.deleteOne(idFilter) else { |
| 86 | + throw Abort(.internalServerError, reason: "Unexpectedly nil response from database") |
| 87 | + } |
| 88 | + guard result.deletedCount == 1 else { |
| 89 | + throw Abort(.notFound, reason: "No kitten with matching _id") |
| 90 | + } |
| 91 | + return Response(status: .ok) |
| 92 | + } catch { |
| 93 | + throw Abort(.internalServerError, reason: "Failed to delete kitten: \(error)") |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + func updateKitten() async throws -> Response { |
| 98 | + let idFilter = try self.getIDFilter() |
| 99 | + // Parse the update data from the request. |
| 100 | + let update = try self.content.decode(KittenUpdate.self) |
| 101 | + /// Create a document using MongoDB update syntax that specifies we want to set a field. |
| 102 | + let updateDocument: BSONDocument = ["$set": .document(try BSONEncoder().encode(update))] |
| 103 | + |
| 104 | + do { |
| 105 | + // since we aren't using an unacknowledged write concern we can expect updateOne to return a non-nil result. |
| 106 | + guard let result = try await self.kittenCollection.updateOne( |
| 107 | + filter: idFilter, |
| 108 | + update: updateDocument |
| 109 | + ) else { |
| 110 | + throw Abort(.internalServerError, reason: "Unexpectedly nil response from database") |
| 111 | + } |
| 112 | + guard result.matchedCount == 1 else { |
| 113 | + throw Abort(.notFound, reason: "No kitten with matching _id") |
| 114 | + } |
| 115 | + return Response(status: .ok) |
| 116 | + } catch { |
| 117 | + throw Abort(.internalServerError, reason: "Failed to update kitten: \(error)") |
| 118 | + } |
| 119 | + } |
| 120 | +} |
0 commit comments