1) 我在Package.swift中设置了以下内容。
.package(url:
"https://github.com/vapor/postgresql.git", from: "1.0.0")
targets: [
.target(name: "App", dependencies: ["FluentSQLite", "Vapor", "PostgreSQL"]),
... etc.
2) 我在configure.swift中配置了PostgreSQL。
let postgreSQLConfig = PostgreSQLDatabaseConfig(
hostname: "localhost",
port: 5432,
username: "postgres",
database: "mydb2",
password: "bigsecret"
)
let psql = PostgreSQLDatabase(config: postgreSQLConfig)
var databases = DatabasesConfig()
databases.add(database: psql, as: .psql)
services.register(databases)
3) 在PostgreSQL 11.3.4中,我有一个名为article的表。
import Foundation
import FluentPostgreSQL
import Vapor
struct Article: PostgreSQLModel {
var id: Int?
var title: String
var content: String
init(id: Int? = nil, title: String, content: String) {
self.title = title
self.content = content
}
}
extension Article: Content {}
extension Article: Migration {}
5) routes.swift看起来像:
let articleController = ArticleController()
router.get("articles", use: articleController.index)
router.post("articles", use: articleController.create)
6) POST和GET都能正常工作(即GET返回我POST的所有内容),但我在PostgreSQL中没有看到表,所以我不知道数据存储在哪里。
import Vapor
import Foundation
final class ArticleController {
func index(_ req: Request) throws -> Future<[Article]> {
return Article.query(on: req).all()
}
func create(_ req: Request) throws -> Future<Article> {
return try req.content.decode(Article.self).flatMap { article in
print("10j")
return article.save(on: req)
}
}
}
Therequest的Content-Type设置为applicationjson,而请求体看起来像。
{"id":1,"title":"GGG","content":"HHH"}
你需要解码一个有效载荷,然后将其保存到数据库中,然后转换为所需的结果。
router.post(at: "article") { req -> EventLoopFuture<String> in
let article = try req.content.decode(Article.self)
return article.create(on: req).transform(to: "what happened?")
}
如果您还没有创建模型,您可以通过在 configure.swift
(以Vapor3为例)
var migrations = MigrationConfig()
migrations.add(model: Article.self, database: .psql)
services.register(migrations)
Artice
模型文件应该是这样的(以Vapor3为例)。
final class Article {
var id: Int?
var title: String
var content: String
init(id: Int? = nil, title: String, content: String) {
self.title = title
self.content = content
}
}
extension Article: Content {}
extension Article: Migration {}
extension Article: Model {
typealias Database = PostgreSQLDatabase
typealias ID = Int
static var idKey: IDKey { \.id }
}
你不能就这样把未来丢掉。这样会引起一系列的问题。
由于一切都是异步的,你需要改变你写代码的方式。相反,你应该做这样的事情。
router.post(Article.self, at: "article") { req, article -> String in
return article.save(on: req).map { savedArticle in
return("what happened?")
}
}
至于为什么保存失败,你应该在控制台中看到打印出来的结果。
我忘了在2)中提到--最后的configure.swift应该有迁移代码,在你运行Xcode时创建表格(或者迁移你在Article.swift中添加或更改的任何列)。
var migrations = MigrationConfig()
migrations.add(model: Article.self, database: .psql)
services.register(migrations)
另外,POST请求体(我在macbook上使用Rested)不应该有PK(PostgreSQL提供PK)。所以。
{"title":"GGG","content":"HHH"}
不
{"id":1,"title":"GGG","content":"HHH"}
谜团解开了.你需要引用表名,因为大写的A:mydb4=# select * from "Article";