简体   繁体   English

在 Heroku 上使用 Vapor 3 配置 PostgreSQL DB

[英]Configure PostgreSQL DB with Vapor 3 on Heroku

I've built a simple Vapor 3 API that I'd like to deploy on Heroku.我已经构建了一个简单的 Vapor 3 API,我想将其部署在 Heroku 上。 I'd like it to be backed by a PostgreSQL database which is also attached to another Heroku app (I have successfully attached the DB in the Heroku dashboard – and the DB works correctly in the other application).我希望它得到一个 PostgreSQL 数据库的支持,该数据库也附加到另一个 Heroku 应用程序(我已经成功地在 Heroku 仪表板中附加了数据库 - 并且该数据库在另一个应用程序中正常工作)。 However, my Vapor app never completes starting up, crashing with the following error:但是,我的 Vapor 应用程序从未完成启动,并因以下错误而崩溃:

Fatal error: Error raised at top level: ⚠️ PostgreSQL Error: no pg_hba.conf entry for host "[the IP addr]", user "[heroku postgres username here]", database "[heroku psql db here]", SSL off
- id: PostgreSQLError.server.fatal.ClientAuthentication

I used vapor heroku init to set up the Heroku app.我使用了vapor heroku init来设置 Heroku 应用程序。 I've Googled around, and tried adding a Procfile and messing with configure.swift , but so far no luck.我已经谷歌搜索,并尝试添加Procfile并弄乱configure.swift ,但到目前为止没有运气。 Here are all the relevant files I can think of:以下是我能想到的所有相关文件:

Procfile:简介:

web: Run serve --env production --hostname 0.0.0.0 --port $PORT --config:postgresql.url $DATABASE_URL

configure.swift:配置.swift:

import FluentPostgreSQL
import Vapor

/// Called before your application initializes.
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
    /// Register providers first
    try services.register(FluentPostgreSQLProvider())

    var contentConfig = ContentConfig.default()

    /// Create custom JSON encoder
    let jsonEncoder = JSONEncoder()
    if #available(OSX 10.12, *) {
        jsonEncoder.dateEncodingStrategy = .iso8601
    } else {
        jsonEncoder.dateEncodingStrategy = .millisecondsSince1970
    }
//    jsonEncoder.keyEncodingStrategy = .convertToSnakeCase

    /// Register JSON encoder and content config
    contentConfig.use(encoder: jsonEncoder, for: .json)
    services.register(contentConfig)

    /// Register routes to the router
    let router = EngineRouter.default()
    try routes(router)
    services.register(router, as: Router.self)

    /// 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)

    // Configure a database
    let dbConfig: PostgreSQLDatabaseConfig
    if let url = Environment.get("DATABASE_URL"), let psqlConfig = PostgreSQLDatabaseConfig(url: url) {
        dbConfig = psqlConfig
    } else {
        dbConfig = PostgreSQLDatabaseConfig(hostname: "localhost", port: 5432, username: "admin", database: "development", password: nil)
    }
    let postgresql = try PostgreSQLDatabase(config: dbConfig)

    /// Register the configured SQLite database to the database config.
    var databases = DatabasesConfig()
    databases.add(database: postgresql, as: .psql)
    services.register(databases)

    /// Configure migrations
    var migrations = MigrationConfig()
    migrations.add(model: Visit.self, database: .psql)
    services.register(migrations)
}

Package.swift:包.swift:

// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "SubwayNyc",
    dependencies: [
        // 💧 A server-side Swift web framework.
        .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"),

        // 🔵 Swift ORM (queries, models, relations, etc) built on PostgreSQL.
        .package(url: "https://github.com/vapor/fluent-postgresql.git", from: "1.0.0"),

        .package(url: "https://github.com/vapor/sql.git", from: "2.1.0")
    ],
    targets: [
        .target(name: "App", dependencies: ["FluentPostgreSQL", "Vapor"]),
        .target(name: "Run", dependencies: ["App"]),
        .testTarget(name: "AppTests", dependencies: ["App"])
    ]
)

How can I get PostgreSQL hooked up to my Vapor 3 app on Heroku?如何将 PostgreSQL 连接到 Heroku 上的 Vapor 3 应用程序?

For Heroku we need unverifiedTLS transport.对于 Heroku,我们需要未经验证的 TLS 传输。

https://api.vapor.codes/postgresql/latest/PostgreSQL/Classes/PostgreSQLConnection/TransportConfig.html https://api.vapor.codes/postgresql/latest/PostgreSQL/Classes/PostgreSQLConnection/TransportConfig.html

let pgURL = Environment.get("DATABASE_URL") ?? "postgres://user:password@host:port/database"

let pgConfig = PostgreSQLDatabaseConfig(url: pgURL, transport: PostgreSQLConnection.TransportConfig.unverifiedTLS)!

:D :D

The original error is the key here, in particular: SSL off .原始错误是这里的关键,特别是: SSL off

This error is thrown by Heroku Postgres when the client is attempting to connect without SSL.当客户端尝试在没有 SSL 的情况下进行连接时,Heroku Postgres 会抛出此错误。 Not familiar with Vapor myself, but a quick look around suggests that configure.swift is where you can make configuration changes.我自己对 Vapor 并不熟悉,但快速浏览一下就会发现configure.swift是您可以进行配置更改的地方。 Once you enable SSL from the client, you should be able to connect to this database instance without issue.从客户端启用 SSL 后,您应该能够毫无问题地连接到此数据库实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM