|
1 | 1 | import FluentPostgreSQL
|
| 2 | +import Foundation |
2 | 3 | import Vapor
|
3 | 4 |
|
4 | 5 | extension Droplet {
|
5 |
| - func postgresDatabase() -> Database { |
6 |
| - let postgresConfig = config["database", "postgres"] |
| 6 | + enum PostgresError: Error { |
| 7 | + case invalidDatabaseURL |
| 8 | + case missingComponent(String) |
| 9 | + } |
| 10 | + |
| 11 | + func postgresDatabase() throws -> Database { |
| 12 | + guard let databaseURL = try config.extract("database", "postgres") as String?, |
| 13 | + let components = URLComponents(string: databaseURL) |
| 14 | + else { |
| 15 | + throw PostgresError.invalidDatabaseURL |
| 16 | + } |
| 17 | + |
| 18 | + let host = components.host ?? "localhost" |
| 19 | + let port = components.port ?? 5432 |
| 20 | + let user = components.user ?? "" |
| 21 | + let password = components.password ?? "" |
7 | 22 |
|
8 |
| - let host = postgresConfig?["host"]?.string ?? "localhost" |
9 |
| - let port = postgresConfig?["port"]?.int ?? 5432 |
10 |
| - let dbname = postgresConfig?["dbname"]?.string ?? "passcards" |
11 |
| - let user = postgresConfig?["user"]?.string ?? "" |
12 |
| - let password = postgresConfig?["password"]?.string ?? "" |
| 23 | + let dbname: String |
| 24 | + if components.path.characters.count > 1 { |
| 25 | + let startPlusOne = components.path.index(after: components.path.startIndex) |
| 26 | + dbname = components.path.substring(from: startPlusOne) |
| 27 | + } else { |
| 28 | + dbname = "passcards" |
| 29 | + } |
13 | 30 |
|
14 | 31 | let postgres = PostgreSQLDriver(host: host, port: port, dbname: dbname, user: user, password: password)
|
15 | 32 | return Database(postgres)
|
|
0 commit comments