gpt4 book ai didi

Swift 和 Vapor : optionally update model field based in reques

转载 作者:行者123 更新时间:2023-11-28 08:11:49 25 4
gpt4 key购买 nike

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

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

这是我的 Controller 中的“编辑”方法:

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
}

在我的 Controller 中,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
}

最佳答案

在您的 Controller 中,您可以执行以下操作:

// 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 呢?和守卫,如果出现故障,您可以中断函数的执行并决定要做什么。

关于Swift 和 Vapor : optionally update model field based in reques,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43574035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com