本文主要是介绍Swift Vapor 教程(CURD 操作),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
接上篇使用 Swift Vapor 对数据库进行简单的操作。
下面会使用一个稍微简单的方式进行 CURD 操作
import Fluent
import Vaporstruct 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 routefunc 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 insong.title = updateSong.titlereturn 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 insong.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
。
这篇关于Swift Vapor 教程(CURD 操作)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!