我使用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
}
是xcode建議工作正常嗎? –