首页 > 其他分享 >【Vapor】06 Chapter 8: Controllers

【Vapor】06 Chapter 8: Controllers

时间:2022-10-24 21:39:06浏览次数:55  
标签:Chapter use get req Controllers api acronyms routes Vapor


0x00 Chapter 8: Controllers

​上篇文章​​​ 把各种路由都写在了 ​​routes.swift​​​ 文件内
如果路由事件太多,​​​routes.swift​​​ 文件就会越来越大
慢慢地就会变得难以管理与维护

所以,如何减轻路由的负担呢?
使用 ​​​Controllers​​ !

使用 ​​Controllers​​​ 还可以对 ​​新旧版本​​​ 的 ​​API​​ 进行区分管理


0x01 创建 Controllers 文件

1.Create the file in ​​Sources/App/Controllers​​​ and call it ​​AcronymsController.swift​

add the following code:

import Fluent
import Vapor

struct AcronymsController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
}
}

create an ​​AcronymsController​​​ that conforms to ​​RouteCollection​


2.Add a new ​​route handler​​​ after ​​boot(routes:)​

struct AcronymsController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
}

func getAllHandler(_ req: Request) throws -> EventLoopFuture<[Acronym]> {
Acronym.query(on: req.db).all()
}
}

3.Register the route in ​​boot(router:)​

struct AcronymsController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
routes.get("api", "acronyms", use: getAllHandler)
}

func getAllHandler(_ req: Request) throws -> EventLoopFuture<[Acronym]> {
Acronym.query(on: req.db).all()
}
}

4.Open ​​routes.swift​​​ and ​​delete​​ the following handler

app.get("api", "acronyms") { req -> EventLoopFuture<[Acronym]> in
Acronym.query(on: req.db).all()
}

5.add the following to the end of ​​routes(_:)​

try app.register(collection: AcronymsController())

经过这 ​​5​​​ 个步骤,就成功的把路由 ​​app.get("api", "acronyms")​​​ 移动到了控制器 ​​AcronymsController​​ 内


0x02 其他路由

在 ​​AcronymsController.swift​​ 内添加其他路由处理方法

  • create
    func createHandler(_ req: Request) throws -> EventLoopFuture<Acronym> {
let acronym = try req.content.decode(Acronym.self)
return acronym.save(on: req.db).map { acronym }
}
  • retrieve a single acronym
    func getHandler(_ req: Request) throws -> EventLoopFuture<Acronym> {
Acronym.find(req.parameters.get("acronymID"), on: req.db)
.unwrap(or: Abort(.notFound))
}
  • update
    func updateHandler(_ req: Request) throws -> EventLoopFuture<Acronym> {
let updatedAcronym = try req.content.decode(Acronym.self)
return Acronym.find(req.parameters.get("acronymID"), on: req.db)
.unwrap(or: Abort(.notFound)).flatMap { acronym in
acronym.short = updatedAcronym.short
acronym.long = updatedAcronym.long
return acronym.save(on: req.db).map {
acronym
}
}
}
  • delete
    func deleteHandler(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
Acronym.find(req.parameters.get("acronymID"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { acronym in
acronym.delete(on: req.db)
.transform(to: .noContent)
}
}
  • filter group
    func searchHandler(_ req: Request) throws -> EventLoopFuture<[Acronym]> {
guard let searchTerm = req.query[String.self, at: "term"] else {
throw Abort(.badRequest)
}

return Acronym.query(on: req.db).group(.or) { or in
or.filter(\.$short == searchTerm)
or.filter(\.$long == searchTerm)
}.all()
}
  • first result
    func getFirstHandler(_ req: Request) throws -> EventLoopFuture<Acronym> {
Acronym.query(on: req.db).first().unwrap(or: Abort(.notFound))
}
  • sorting results
    func sortedHandler(_ req: Request) throws -> EventLoopFuture<[Acronym]> {
Acronym.query(on: req.db).sort(\.$short, .ascending).all()
}

最后进行路由与方法的注册

    func boot(routes: RoutesBuilder) throws {
routes.get("api", "acronyms", use: getAllHandler)
routes.post("api", "acronyms", use: createHandler)
routes.get("api", "acronyms", ":acronymID", use: getHandler)
routes.put("api", "acronyms", ":acronymID", use: updateHandler)
routes.delete("api", "acronyms", ":acronymID", use: deleteHandler)
routes.get("api", "acronyms", "search", use: searchHandler)
routes.get("api", "acronyms", "first", use: getFirstHandler)
routes.get("api", "acronyms", "sorted", use: sortedHandler)
}

0x03 路由组 - Route groups

在注册路由对应的方法时
会重复写 ​​​"api", "acronyms"​​​ 这些可以通过一个路由组来管理
减少重复代码

    func boot(routes: RoutesBuilder) throws {
// routes.get("api", "acronyms", use: getAllHandler)
// routes.post("api", "acronyms", use: createHandler)
// routes.get("api", "acronyms", ":acronymID", use: getHandler)
// routes.put("api", "acronyms", ":acronymID", use: updateHandler)
// routes.delete("api", "acronyms", ":acronymID", use: deleteHandler)
// routes.get("api", "acronyms", "search", use: searchHandler)
// routes.get("api", "acronyms", "first", use: getFirstHandler)
// routes.get("api", "acronyms", "sorted", use: sortedHandler)

let acronymsRoutes = routes.grouped("api", "acronyms")
acronymsRoutes.get(use: getAllHandler)
acronymsRoutes.post(use: createHandler)
acronymsRoutes.get(":acronymID", use: getHandler)
acronymsRoutes.put(":acronymID", use: updateHandler)
acronymsRoutes.delete(":acronymID", use: deleteHandler)
acronymsRoutes.get("search", use: searchHandler)
acronymsRoutes.get("first", use: getFirstHandler)
acronymsRoutes.get("sorted", use: sortedHandler)
}

0x04 我的作品

欢迎体验我的作品之一:​​小五笔​​​ 五笔学习好帮手~
​App Store​​ 搜索即可~



标签:Chapter,use,get,req,Controllers,api,acronyms,routes,Vapor
From: https://blog.51cto.com/u_15844020/5791286

相关文章

  • 【Vapor】05 Chapter 7: CRUD Database Operations
    0x00Chapter7:CRUDDatabaseOperations在​​routes.swift​​​文件内写各种路由操作数据库的记录1.create创建记录,之前的文章已经写过了需要提交数据url:​​ht......
  • 【Vapor】04 Chapter 6:Configuring a Database
    0x00Chapter6:ConfiguringaDatabase1.​​Vapor​​​hasofficial,Swift-native​​drivers​​for:SQLiteMySQLPostgreSQLMongoDB2.数据库类型:关系型(relational):​......
  • Python_fifth_chapter_homework
    Python第五章实例和实战作业实例01:使用字符串拼接输出一个关于程序员的笑话代码如下:代码运行结果如下: 实例02:截取身份证号码中的出生日期代码如下:代码运行......
  • 引擎之旅 Chapter.4 日志系统
    关于近段时间为何没有更新的解释:Findanewjob.目录引言日志语句的分类控制台窗体和VSOutputTab的日志打印存储至特定的文件中展示堆栈信息引言一般来说,一个优质......
  • English words chapter 20220927
    作者:​DATA_MONK​​​......
  • aPtCfU - Chapter1 Solutions
    1.\(f(1)+f(2)+\cdots+f(1999)\)为奇数当且仅当\(2001,2003\)一共被加了奇数次.那么枚举它们一共被选了\(1,3,5,...,1999\)次,最终答案为\[\sum_{i=0}^{999}{1......
  • English words chapter 20220927
    ......
  • JVM-Chapter_4_程序计数器
    PCRedister介绍JVM中的程序计数寄存器(ProgramCounterRegister)中,Register的命名源于CPU的寄存器,寄存器存储指令相关的现场信息。CPU只有把数据装载到寄存器才能够......
  • 《JavaScript高级程序设计》Chapter04 Variable,Scope,Memory
    原始值&引用值原始值(primitivevalue):Undefined,Null,Boolean,Number,String,Symbol按值访问,直接操作存储在变量中的实际值引用值(referencevalue):Object......
  • JVM-Chapter_2_类加载子系统
    类加载子系统的作用类加载子系统负责从文件系统或者网络中加载class文件,class文件在文件的开头有特定的文件标识。ClassLoader只负责class文件的加载,至于它是否可以运行......