2017-04-23 86 views
0

我使用Swift和Vapor(服务器端)创建基本CRUD。Swift with Vapor:可选更新基于请求的模型字段

在我的控制器中,我创建了一个新的方法:“编辑”。在这种方法中,可以更新用户的密码和角色。 如果请求有密码数据,更新密码。 IF请求有一个新的角色数组,更新角色(兄弟姐妹关系至今尚未完成)。

这是在我的控制器中的“编辑”的方法:

func edit(request:Request, id:String) throws -> ResponseRepresentable { 
    // Check if the password came in POST request: 
    let password = request.data["password"]?.string 

    // Check if the request has a new set of roles 
    let roles = request.data["roles"]?.array 

    let user:ClinicUser = try ClinicUser.edit(id: id, password: password, roles: roles) 
    return user 
} 

而且在我的模型编辑方法是这样的:

static func edit(id:String, password:String?, roles:Array<NodeRepresentable>?) throws -> ClinicUser { 
    guard var user:ClinicUser = try ClinicUser.find(id) else { 
     throw Abort.notFound 
    } 
    // Is it the best way of doing this? Because with "guard" I should "return" or "throw", right? 
    if password != nil { 
     user.password = try BCrypt.hash(password: password!) 
    } 

    // TODO: update user's roles relationships 

    try user.save() 

    return user 
} 

在我的控制,有通过指出错误表示Cannot convert value of type '[Polymorphic]?' to expected argument type 'Array<NodeRepresentable>'的XCode。而且,作为修复,Xcode中提出这样写:

let user:ClinicUser = try ClinicUser.edit(id: id, password: password, roles: roles as! Array<NodeRepresentable>) 

我不知道这是否是安全的,或者如果这是一个最好的做法(强制解包与!)。

我不知道在Swift中我是否应该“思考”与其他语言(比如PHP等)不同。最后,我要的是:

static func edit(id:String, fieldA:String?, fieldN:String, etc..) throws -> ClinicUser { 
    // If fieldA is available, update fieldA: 
    if fieldA != nil { 
     model.fieldA = fieldA 
    } 

    // If fieldN is available, update fieldN: 
    if fieldN != nil { 
     model.fieldN = fieldN 
    } 

    // After update all fields, save: 
    try model.save() 

    // Return the updated model: 
    return model 
} 
+0

是xcode建议工作正常吗? –

回答

0

在你的控制器,你可以做到以下几点:

// Check if the request has a new set of roles 
let rolesArray = request.data["roles"]?.array 
guard let roles = rolesArray as? Array<NodeRepresentable> 
else { 
    // throw "SomeError" or return "Some other response" 
} 

Xcode的抱怨,因为它不能说明你得到了数组类型您的请求数据在编译时。

因此,您必须将其向下转换为更具体的类型。

您有两种选择。

  1. as! - >如果失败会触发运行时错误
  2. as? - >如果失败会返回nil

那么如果你使用as?并警惕,如果发生故障,您可以中断您的功能执行并决定您想要执行的操作。