【Vapor】06 Chapter 8: Controllers
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 Vaporstruct 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]> inAcronym.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 inacronym.short = updatedAcronym.shortacronym.long = updatedAcronym.longreturn 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 inacronym.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 inor.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
搜索即可~
【Vapor】06 Chapter 8: Controllers相关推荐
- 【Vapor】03 Chapter 5: Fluent Persisting Models
0x00 Chapter 5: Fluent & Persisting Models 1.Fluent is Vapor's ORM or object relational mapping ...
- 【Vapor】07 Chapter 9: Parent-Child Relationships
0x00 Chapter 9: Parent-Child Relationships 1.Parent-child relationships describe a relationship wher ...
- 【Vapor】04 Chapter 6:Configuring a Database
0x00 Chapter 6:Configuring a Database 1.Vapor has official, Swift-native drivers for: SQLite MySQL P ...
- 【Vapor】05 Chapter 7: CRUD Database Operations
0x00 Chapter 7: CRUD Database Operations 在 routes.swift 文件内写各种路由 操作数据库的记录 1.create 创建记录,之前的文章已经写过了 需 ...
- 【rust】| 06——语言特性 | 所有权
系列文章目录 [rust]| 00--开发环境搭建 [rust]| 01--编译并运行第一个rust程序 [rust]| 02--语法基础 | 变量(不可变?)和常量 [rust]| 03--语法基础 ...
- 【JAVA】06 封装、继承、多态 总结(初级)
教程:B站韩顺平 目录 一.访问修饰符 二.封装 三.继承 3.1 继承 3.1.1 super关键字 3.2 继承 3.2.1 概念 3.2.2 继承的本质 3.2.3 方法重写/覆盖 3.2.3. ...
- 【Python】06 - 常用文件处理(txt、excel [xlsx、xls])
目录 一.文件概述 二.文本文件操作 2.1 文件打开 2.2 文件的关闭 2.3 文件的读.写操作 1) 读取方法 2)写入方法 2.4 读写指针的重定位 2.5 其它文本文件 三.Excel文件处 ...
- 【翻译】Chemkin - Chapter 1
[这段文字是2013年3月翻译的,整理老文档时发现就拿出来,提醒我们:任何试图翻译英文手册的尝试都是徒劳的] 第一章 介绍 Chemkin理论手册提供了一个对关系和公式的宽泛的概览,这些关系和公式 ...
- 【青少年编程】【Scratch】06 侦测模块
06 侦测模块 侦测模块是用来检测场景中某一参数的变化,通过参数变化来为下一步操作提供运行依据.通常与控制模块中的条件语句和循环语句一起使用. 具体分为: 与运动相关的侦测: 与按键相关的侦测: 侦测 ...
最新文章
- 主席树 ---- LCA(树上第k大)Count on a tree
- 第三章:Python基础の函数和文件操作实战
- flutter实现(OutlineButton)线框按钮
- arm clz指令c语言,协处理器及其他指令之:零计数指令CLZ-嵌入式系统-与非网
- java和ssm是什么关系,JAVA --- SSH和SSM的区别
- FL2440移植LINUX-3.4.2 -- 按键驱动和触摸屏驱动移植
- 基于JavaScript技术的横排文字转古书式竖排工具
- SpringBoot2 整合Ehcache组件,轻量级缓存管理
- java信号灯_java 信号灯 Semaphore
- B - Friends
- 《AutoCAD 2016中文版从入门到精通》——1.5 基本输入操作
- Jquery实现鼠标双击Table单元格变成文本框
- 通过物理模型生成Java代码
- 系统调用跟我学(4)
- 博客开篇第一篇--资深前端工程师
- 借助WinPE进行Windows系统安装
- 对PBFT算法的理解
- 西奥电梯服务器无响应,干货│西奥电梯故障分析和技术文件
- 约瑟夫环(简单理解版)
- 解读中国版新资本协议