2017-06-12 25 views
1

我對Vapor 2.0服務器端Swift框架非常熟悉,並且讓我困惑的是大量使用字符串文字。例如,實施Model協議,你必須分析和序列這樣的行(從自動生成的示例項目採取):Vapor中的數據庫列名

// Initializes the Post from the database row 
init(row: Row) throws { 
    content = try row.get("content") 
} 

// Serializes the Post to the database 
func makeRow() throws -> Row { 
    var row = Row() 
    try row.set("content", content) 
    return row 
} 

正如你所看到的,對於每一個屬性,你使用它的數據庫名稱兩次作爲一個字符串文字只是爲了這個特定的協議。在其他情況下還有更多 - 例如,Database協議,您自己的方法等。

使用文字字符串作爲參數在這裏有明顯的缺點,靜態分析器不檢查它們(就像Objective-C中的鍵值參數),使這種方法極易出錯。有沒有我錯過的最佳做法?

回答

1

您可以很容易地將重複字符串的次數最小化,方法是將其作爲靜態屬性存儲在模型中,然後引用該字符串。

final class Post: Model { 
    // Keys 
    static let contentKey = "content" 

    // Properties 
    var content: String 

    // Initializes the Post from the database row 
    init(row: Row) throws { 
     content = try row.get(Post.contentKey) 
    } 

    // Serializes the Post to the database 
    func makeRow() throws -> Row { 
     var row = Row() 
     try row.set(Post.contentKey, content) 
     return row 
    } 

    ... 
} 

extension Post: Preparation { 
    static func prepare(_ database: Database) throws { 
     try database.create(self) { builder in 
      builder.id() 
      builder.string(Post.contentKey) 
     } 
    } 

    ... 
} 

不幸的是,這可能是所有你可以做的更有意義的事情,使事情更安全。目前沒有辦法給編譯器提供關於數據庫實際結構的信息(或者任何其他字符串的東西,比如JSON)。但是,如果我們能夠做到這一點,那將會非常棒!也許有一天。

(我會考慮更新API和Web模板來包括這一點,在這裏追蹤問題:https://github.com/vapor/api-template/issues/35

+0

API模板已更新爲像這樣工作。 :) https://github.com/vapor/api-template/pull/36 – tanner0101

0

不!你做對了。由於Swift中缺少高級運行時庫,我們很難做到這一點。

但是,在Swift 4中,您可以使用鍵路徑來達到同樣的目的。

\Post.content將爲內容變量創建靜態檢查的鍵路徑。

關鍵路徑上的WWDC會話絕對值得一看。

+0

謝謝你的建議,要收看會議肯定的! –