【问题标题】:Manually modifying model property values in vapor 4 response在蒸汽 4 响应中手动修改模型属性值
【发布时间】:2020-08-05 09:19:41
【问题描述】:

我有一个 Vapor 4 应用程序。我从数据库进行查询以获取一些项目,并且我想在完成请求之前根据返回的值执行一些手动计算。这是我想要实现的示例代码。

final class Todo: Model, Content {

    static var schema: String = "todos"

    @ID(custom: .id)
    var id: Int?

    @Field(key: "title")
    var title: String

    var someValue: Int?

}

/// Allows `Todo` to be used as a dynamic migration.
struct CreateTodo: Migration {
    func prepare(on database: Database) -> EventLoopFuture<Void> {
        database.schema(Todo.schema)
            .field("id", .int, .identifier(auto: true))
            .field("title", .string, .required)
            .create()
    }

    func revert(on database: Database) -> EventLoopFuture<Void> {
        database.schema(Todo.schema).delete()
    }
}
final class TodoController:RouteCollection{

    func boot(routes: RoutesBuilder) throws {

        routes.get("tmp", use: temp)
    }

    func temp(_ req:Request) throws -> EventLoopFuture<[Todo]> {

        Todo.query(on: req.db).all().map { todos in

            todos.map {
                $0.someValue = (0...10).randomElement()!
                return $0
            }
        }
    }

}

问题是这些手动更改无法响应。在本例中为 someValue 属性。

谢谢。

[
    {
        "title": "item 1",
        "id": 1
    },
    {
        "title": "item 2",
        "id": 2
    }
]

【问题讨论】:

    标签: swift vapor server-side-swift vapor-fluent


    【解决方案1】:

    您遇到的问题是 Models 覆盖了 Codable 实现。这允许你做一些事情,比如传递父母而不添加孩子等。

    但是,这打破了你的情况。你应该做的是创建一个新类型,如果你想返回一个 Todo 并带有另一个未存储在数据库中的字段,例如:

    struct TodoResponse: Content {
      let id: Int
      let title: String
      let someValue: Int
    }
    

    然后在路由处理程序中从您的数据库类型转换为您的响应类型(这是一种非常常见的模式,并且推荐在 Vapor 中执行此操作)

    【讨论】:

      猜你喜欢
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      相关资源
      最近更新 更多