關(guān)于web框架视搏、這里使用vapor
使用 vapor --help
命令我們可以看到有幾種模板可供我們使用。
- 這里也主要是使用這些來(lái)搭建互例。
Api模板
vapor new Hello --template=api
Web模板
vapor new Hello --template=api
因?yàn)橛心0澹詴?huì)簡(jiǎn)單很多。
這里不再進(jìn)行編寫(xiě)ORM愈犹,這里介紹一下vapor的Fluent
如果出錯(cuò)可以看官方文檔
- Fluent provides an easy, simple, and safe API for working with your persisted data. Each database table/collection is represented by a Model that can be used to interact with the data. Fluent supports common operations like creating, reading, updating, and deleting models. It also supports more advanced operations like joining, relating, and soft deleting.
谷歌翻譯一下,大致如下闻丑。
- Flunet提供了一個(gè)容易漩怎,簡(jiǎn)單勋颖,安全的API來(lái)處理你的持久數(shù)據(jù)。 每個(gè)數(shù)據(jù)庫(kù)表/集合由可用于與數(shù)據(jù)交互的模型表示勋锤。 Fluent支持常見(jiàn)操作饭玲,如創(chuàng)建,讀取怪得,更新和刪除模型咱枉。 它還支持更高級(jí)的操作,如加入徒恋,關(guān)聯(lián)和軟刪除蚕断。
反正就是不用自己寫(xiě)SQL語(yǔ)句就能進(jìn)行數(shù)據(jù)的增刪改查。
創(chuàng)建一個(gè)Model
- 這里是OC NSKeyedArchiver(歸檔) 差不多入挣,需要實(shí)現(xiàn)一個(gè)協(xié)議亿乳。
final class Pet: Model {
var name: String
var age: Int
let storage = Storage()
init(name: String, age: Int) {
self.name = name
self.age = age
}
init(row: Row) throws {
name = try row.get("name")
age = try row.get("age")
}
func makeRow() throws -> Row {
var row = Row()
try row.set("name", name)
try row.set("age", age)
return row
}
}
Storage
存儲(chǔ)屬性允許添加額外的屬性,比如數(shù)據(jù)庫(kù)id
The
storage
property is there to allow Fluent to store extra information on your model--things like the model's database id.
Row
The Row
struct represents a database row. Your models should be able to parse from and serialize to database rows.
Preparing the Database
In order to use your model, you may need to prepare your database with an appropriate schema.
Preparation
Most databases, like SQL databases, require the schema for a model to be created before it is stored. Adding a preparation to your model will allow you to prepare the database while your app boots.
大多數(shù)數(shù)據(jù)庫(kù)都要求在存儲(chǔ)數(shù)據(jù)之前創(chuàng)建模型径筏。所以這里需要預(yù)處理
extension Pet: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { pets in
pets.id()
pets.string("name")
pets.int("age")
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}