带有 Vapor 的 Swift:可选择根据请求更新模型字段

问题描述 投票:0回答:1

我正在使用 Swift 和 Vapor(服务器端)创建基本的 CRUD。

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

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

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
}

在我的控制器中,XCode 指出了一个错误,提示为

Cannot convert value of type '[Polymorphic]?' to expected argument type 'Array<NodeRepresentable>'
。并且,作为修复,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
}
swift vapor
1个回答
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. 作为! -> 如果失败将会触发运行时错误
  2. 作为? ->如果失败将返回nil

那么如果你使用as?并守卫,如果出现故障,您可以中断函数的执行并决定您想要做什么。

© www.soinside.com 2019 - 2024. All rights reserved.