項(xiàng)目初始化
- 安裝Vapor Tools
- 使用Vapor Tools初始化項(xiàng)目
注意:可以根據(jù)需求創(chuàng)建模板項(xiàng)目vapor new <name> [--template]
Name | Flag | Descripiton |
---|---|---|
API | --template=api | JSON API with Fluent database. |
Web | --template=web | HTML website with Leaf templates. |
查看更多模板
- MySQL的配置
- 在
Package.swift
文件添加文件路徑:
.Package(url: "https://github.com/vapor/mysql-provider.git", majorVersion: 2)
- 添加到
Droplet
中,在文件Config+Setup.swift
進(jìn)行添加操作
try addProvider(MySQLProvider.Provider.self)
- 在文件夾
Config
下創(chuàng)建mysql.json,以json的形式設(shè)置服務(wù)地址數(shù)據(jù)庫名與密碼
{ "hostname" : "localhost", "user" : "root", "password" : "", "database" : "test"}
- 在fluent.json中將
"driver": "memory"
改為"driver":"mysql"
- 在
- MySQL的使用
- 直接使用SQL語句
get("mysql") { req in let mysql = try self.mysql() let version = try mysql.raw("select * from users") let json = JSON(node:version.wrapped) return json }
- 使用Fluent轉(zhuǎn)為關(guān)系型數(shù)據(jù)庫
- 創(chuàng)建繼承自
FluentProvider
中間件的Model
類User
,并實(shí)現(xiàn)RowConvertible
協(xié)議
final class User: Model { /// General implementation should just be `let storage = Storage()` /// The storage property is there to allow Fluent to store extra information on your model--things like the model's database id. var storage: Storage = Storage() var number:Int var name:String var password:String var avatar:String static let idKey: String = "id" static let numberKey:String = "number" static let nameKey:String = "name" static let pwdKey:String = "password" static let avatarKey:String = "avatar" init(number:Int, name:String, password: String, avatar:String) { self.number = number self.name = name self.password = password self.avatar = avatar } func makeRow() throws -> Row { var row = Row() try row.set(User.numberKey, number) try row.set(User.nameKey, name) try row.set(User.pwdKey, password) try row.set(User.avatarKey, avatar) return row } init(row: Row) throws { number = try row.get(User.numberKey) name = try row.get(User.nameKey) password = try row.get(User.pwdKey) avatar = try row.get(User.avatarKey) } }
- 數(shù)據(jù)庫初始化
extension User:Preparation { /// The revert method should undo any actions /// caused by the prepare method. /// /// If this is impossible, the `PreparationError.revertImpossible` /// error should be thrown. static func revert(_ database: Database) throws { try database.delete(self) } /// The prepare method should call any methods /// it needs on the database to prepare. static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.int(User.numberKey) builder.string(User.nameKey) builder.string(User.pwdKey) builder.string(User.avatarKey) } } }
- 添加到Droplet中
在Config+Setup.swift
文件中setupPreparations
方法中添加User數(shù)據(jù)庫初始化
/// Add all models that should have their /// schemas prepared before the app boots private func setupPreparations() throws { preparations.append(Post.self) preparations.append(User.self) }
- Fluent數(shù)據(jù)操作
static func login(_ request: Request) -> ResponseRepresentable { do { guard let name = request.parameters.wrapped["username"]?.string ,let pwd = request.parameters.wrapped["password"]?.string else { return Response(status: .badRequest, body: "Failed") } // 查詢篩選 guard let _ = try User.makeQuery().filter(raw: "name = \"\(name)\" and password = \"\(pwd)\"").first() else { return Response(status: .notFound, body: "not exist or wrong password") } return Response(status: .ok, body: "ok") } catch { return Response(status: Status(statusCode: 555, reasonPhrase: "exception error"), body: error.localizedDescription) } } static func register(_ request: Request) -> ResponseRepresentable { do { guard let name = request.parameters.wrapped["username"]?.string ,let pwd = request.parameters.wrapped["password"]?.string ,let avatar = request.parameters.wrapped["avatar"]?.string else { return Response(status: .badRequest, body: "Failed") } if let _ = try User.makeQuery().filter("name",name).first() { return Response(status: Status(statusCode: 444, reasonPhrase: "Had exists"), body: "Had exists") } let date = Date() let number = Int(date.timeIntervalSince1970) let user = User(number: number, name: name, password: pwd, avatar: avatar) // 保存 try user.save() return Response(status: .ok, body: "Success") } catch { return Response(status: Status(statusCode: 555, reasonPhrase: "exception error"), body: error.localizedDescription) } }
- 創(chuàng)建繼承自
-
Fluent與MySQL的關(guān)系
更多Fluent
點(diǎn)我查看