Vapor 2模型到JSON失败

时间:2017-11-27 18:07:35

标签: json model vapor

目前有一个类有两个嵌套的变量,它们是结构类型。当我发布到控制器时,我通过使用以下方法将帖子主体映射到对象来验证JSON:

extension Request {
func user() throws -> User {
    guard let json = json else { throw Abort.badRequest }
    do {
        return try User(json: json)
    } catch  {
        throw Abort.init(.notAcceptable, metadata: nil, reason: "\(json.wrapped)", identifier: nil, possibleCauses: nil, suggestedFixes: nil, documentationLinks: nil, stackOverflowQuestions: nil, gitHubIssues: nil)
    }
}
}

哪个电话:

extension User: JSONInitializable {
  convenience init(json: JSON) throws {
    try self.init(
        type: json.get("type"),
        person: json.get("person")
    )
  }
}

问题是我从Request.user()方法得到了throw错误。我的模型是可靠的,我已经检查了针对person对象的JSON响应。此刻的人是:

  struct Person {
   var firstName: String
   var lastName: String
   var email: String
   var password: String
   var address: Address 
}

extension Person: JSONInitializable {
 init(json: JSON) throws {
    try self.init(
        firstName: json.get("firstName"),
        lastName: json.get("lastName"),
        email: json.get("email"),
        password: json.get("password"),
        address: json.get("address")
    )
  }
}

这是非常基本的,所以应该通过映射验证。此结构是否还需要符合Vapor Model subclass才能正确映射或者是否存在其他错误?

编辑:添加用户

final class User: Model {

let storage = Storage()
var type: String
var person: Person

init(type: String, person: Person) {
    self.type   = type
    self.person = person
}

//MARK: Parse row from the database
init(row: Row) throws {
    type = try row.get("type")
    person = try row.get("person")
}

//MARK: Adding a row to the database
func makeRow() throws -> Row {
    var row = Row()
    try row.set("person", person)
    try row.set("type", type)
    try row.set("country", person.address.country)
    return row
}

}

extension User: JSONInitializable {

// MARK: Will be the request in json format
convenience init(json: JSON) throws {
    try self.init(
        type: json.get("type"),
        person: json.get("person")

    )
}
}

extension User: Timestampable, SoftDeletable, JSONConvertible {

//MARK: Convert user to json to pass back
func makeJSON() throws -> JSON {
    var json = JSON()
    try json.set("id", id)
    try json.set("type", type)
    try json.set("person", person)
    return json
}

}

// Fluent DB Preparation
extension User: Preparation {

static func prepare(_ database: Database) throws {
    try database.create(self) { builder in
        builder.id()
        builder.string("person")
        builder.string("type")
        builder.string("country")
    }
}

static func revert(_ database: Database) throws {
    try database.delete(self)
}
}

extension User: ResponseRepresentable, NodeRepresentable {}

0 个答案:

没有答案