2017-04-23 5 views
0

SwiftとVapor(サーバー側)を使用して基本的なCRUDを作成しています。 「編集」:私のコントローラでSwift with Vapor:オプションでモデルフィールドを更新します。

は、私は新しいメソッドを作成しました。この方法では、ユーザーのパスワードと役割を更新することができます。 IF要求にパスワードデータがある場合は、パスワードを更新します。 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>) 

私はこれが安全であるかどうかわからないですか、これはそれがベストプラクティスである場合は(でアンラップを強制!)。

スウィフトに、私は他の言語とは異なる「考える」必要がある場合、私は知りません(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

あなたは次の操作を行うことができます:

それはあなたが外になっているアレイのタイプを指定することはできませんので、Xcodeのは文句
// 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" 
} 

をコンパイル時にリクエストデータ。あなたはより具体的な型にダウンキャストしなければならない結果

あなたには2つの選択肢があります。

  1. として! - >失敗するとランタイムエラーが発生する
  2. as? - それはあなたのように使用している場合

を失敗した場合> nilを返しますか?失敗した場合は、関数の実行を中断して、実行したいことを決めることができます。

関連する問題