Hello Vapor

项目初始化

  1. 安装Vapor Tools
  2. 使用Vapor Tools初始化项目
    注意:可以根据需求创建模板项目vapor new [--template]
Name Flag Descripiton
API --template=api JSON API with Fluent database.
Web --template=web HTML website with Leaf templates.

查看更多模板

  1. MySQL的配置
    • Package.swift文件添加文件路径:
      .Package(url: "https://github.com/vapor/mysql-provider.git", majorVersion: 2)
    • 添加到Droplet中,在文件Config+Setup.swift进行添加操作
      try addProvider(MySQLProvider.Provider.self)
    • 在文件夹Config下创建mysql.json,以json的形式设置服务地址数据库名与密码
      { "hostname" : "localhost", "user" : "root", "password" : "", "database" : "test"}
    • 在fluent.json中将"driver": "memory"改为"driver":"mysql"
  2. 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转为关系型数据库
      • 创建继承自FluentProvider中间件的ModelUser,并实现RowConvertible协议
      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)
          }
      }
      
      • 数据库初始化
       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数据库初始化
        /// 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数据操作
       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)
            }
        }
      
  3. Fluent与MySQL的关系


    Hello Vapor_第1张图片
    Fluent&MySQL.png

更多Fluent点我查看

你可能感兴趣的:(Hello Vapor)