Skip to content

Commit f82873b

Browse files
committed
Pass PostgreSQL credentials through DATABASE_URL
1 parent ac76f89 commit f82873b

File tree

4 files changed

+27
-22
lines changed

4 files changed

+27
-22
lines changed

Config/development/database.json

+1-7
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,3 @@
11
{
2-
"postgres": {
3-
"host": "localhost",
4-
"port": 5432,
5-
"dbname": "passcards",
6-
"user": "$USER",
7-
"password": ""
8-
}
2+
"postgres": "postgres://$USER:@0.0.0.0:5432/passcards"
93
}

Config/production/database.json

+1-7
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,3 @@
11
{
2-
"postgres": {
3-
"host": "$PG_HOST",
4-
"port": "$PG_PORT",
5-
"dbname": "$PG_DBNAME",
6-
"user": "$PG_USER",
7-
"password": "$PG_PASSWORD"
8-
}
2+
"postgres": "$DATABASE_URL"
93
}

Sources/App/Droplet+Database.swift

+24-7
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,32 @@
11
import FluentPostgreSQL
2+
import Foundation
23
import Vapor
34

45
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 ?? ""
722

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+
}
1330

1431
let postgres = PostgreSQLDriver(host: host, port: port, dbname: dbname, user: user, password: password)
1532
return Database(postgres)

Sources/App/main.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import Storage
33
import Vapor
44

55
let drop = Droplet()
6-
drop.database = drop.postgresDatabase()
6+
drop.database = try drop.postgresDatabase()
77
drop.preparations = [Pass.self, Registration.self]
88

99
try drop.addProvider(StorageProvider.self)

0 commit comments

Comments
 (0)