Swift Vapor 教程(CURD 操作)

接上篇使用 Swift Vapor 对数据库进行简单的操作。
下面会使用一个稍微简单的方式进行 CURD 操作

import Fluent
import Vapor

struct SongController: RouteCollection {
    
    func boot(routes: Vapor.RoutesBuilder) throws {
        let songs = routes.grouped("songs")
        
        //  GET http://127.0.0.1:8080/songs
        // 获取所有列表
        songs.get(use: index)
        
        // POST  http://127.0.0.1:8080/songs
        // 单个插入
        // 参数如下:
        //    {
        //       "title": "ka qiu sha"
        //    }
        songs.post(use: create)
        
        // http://127.0.0.1:8080/songs/A73796AE-D7DE-4042-AD08-2194FBE4C0BA
        // GET /users/:userID(这个:userID 是真实的 id)
        // 更加id 获取单条信息
        songs.get(":songID", use: show)
                
        // http://127.0.0.1:8080/songs/A73796AE-D7DE-4042-AD08-2194FBE4C0BA
        // DELETE /users/:userID(这个:userID 是真实的 id)
        // 删除(根据id删除)
        songs.delete(":songID", use: delete)
        
        // http://127.0.0.1:8080/songs/45F40F36-69E5-4C28-8462-D6271C9A054F
        // 参数如下:
        // {
        //  "title": "qiang jun zhan ge"
        //  }
        // PUT /users/:userID(这个:userID 是真实的 id)
        // 更新信息(根据id更新)
        songs.put(":songID", use: update)
        
    }
    
    
    //  GET Request /songs route
    func index(req: Request) throws -> EventLoopFuture<[Song]> {
        // 查询所有
        return Song.query(on: req.db).all()
    }
    
    //  POST Request /songs create 增
    func create(req: Request) throws -> EventLoopFuture<HTTPStatus> {
        let song = try req.content.decode(Song.self)
        return song.save(on: req.db).transform(to: .ok)
    }
    
    
    func show(req: Request) throws -> EventLoopFuture<Song> {
        return Song.find(req.parameters.get("songID"), on: req.db)
            .unwrap(or: Abort(.notFound))
    }
    
    func update(req: Request) throws -> EventLoopFuture<Song> {
        let updateSong = try req.content.decode(Song.self)
        return Song.find(req.parameters.get("songID"), on: req.db)
            .unwrap(or: Abort(.notFound)).flatMap { song in
                song.title = updateSong.title
                return song.save(on: req.db).map { song }
            }
    }
    
    func delete(req: Request) throws -> EventLoopFuture<HTTPStatus> {
        return Song.find(req.parameters.get("songID"), on: req.db)
            .unwrap(or: Abort(.notFound)).flatMap { song in
                song.delete(on: req.db).transform(to: .ok)
            }
    }
    
}

创建用户:POST /songs,带上 JSON 请求体,比如

{
    "title": "zhong guo ren"
}

列出所有用户:GET /songs
获取单个用户:GET /songs/:songID
更新用户信息:PUT /songs/:songID
删除用户:DELETE /songs/:songID

你可能感兴趣的:(iOS,之旅,swift,开发语言,ios)