|
1 | 1 | import Kitura |
2 | 2 | import MongoSwift |
| 3 | +import NIO |
3 | 4 |
|
4 | 5 | /// A Codable type that matches the data in our home.kittens collection. |
5 | | -private struct Kitten: Codable { |
| 6 | +struct Kitten: Codable { |
6 | 7 | var name: String |
7 | 8 | var color: String |
8 | 9 | } |
9 | 10 |
|
10 | | -/// A single collection with type `Kitten`. This allows us to directly retrieve instances of |
11 | | -/// `Kitten` from the collection. `MongoCollection` is safe to share across threads. |
12 | | -private let collection = try MongoClient().db("home").collection("kittens", withType: Kitten.self) |
| 11 | +// Create a single EventLoopGroup for Kitura and the MongoClient to share. |
| 12 | +let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 4) |
| 13 | +let mongoClient = try MongoClient(using: eventLoopGroup) |
13 | 14 |
|
14 | | -private let router: Router = { |
| 15 | +defer { |
| 16 | + mongoClient.syncShutdown() |
| 17 | + cleanupMongoSwift() |
| 18 | + try? eventLoopGroup.syncShutdownGracefully() |
| 19 | +} |
| 20 | + |
| 21 | +let router: Router = { |
15 | 22 | let router = Router() |
16 | 23 |
|
17 | | - router.get("kittens") { _, response, _ in |
18 | | - let cursor = try collection.find() |
19 | | - let results = Array(cursor) |
20 | | - if let error = cursor.error { |
21 | | - throw error |
| 24 | + /// A single collection with type `Kitten`. This allows us to directly retrieve instances of |
| 25 | + /// `Kitten` from the collection. `MongoCollection` is safe to share across threads. |
| 26 | + let collection = mongoClient.db("home").collection("kittens", withType: Kitten.self) |
| 27 | + |
| 28 | + router.get("kittens") { _, response, next -> Void in |
| 29 | + let res = collection.find().flatMap { cursor in |
| 30 | + cursor.toArray() |
| 31 | + } |
| 32 | + |
| 33 | + res.whenSuccess { results in |
| 34 | + response.send(results) |
| 35 | + next() |
| 36 | + } |
| 37 | + |
| 38 | + res.whenFailure { error in |
| 39 | + response.error = error |
| 40 | + response.send("Error: \(error)") |
| 41 | + next() |
22 | 42 | } |
23 | | - response.send(results) |
24 | 43 | } |
25 | 44 |
|
26 | 45 | return router |
27 | 46 | }() |
28 | 47 |
|
29 | | -Kitura.addHTTPServer(onPort: 8080, with: router) |
| 48 | +let server = Kitura.addHTTPServer(onPort: 8080, with: router) |
| 49 | +// Use the EventLoopGroup created above for the Kitura server. To call this method we must build with |
| 50 | +// `export KITURA_NIO=1 && swift build`. |
| 51 | +try server.setEventLoopGroup(eventLoopGroup) |
30 | 52 | Kitura.run() |
0 commit comments