我使用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建议工作正常吗? –