【Vapor】06 Chapter 8: Controllers

【Vapor】06 Chapter 8: Controllers,第1张

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 {
        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.find(req.parameters.get("acronymID"), on: req.db)
            .unwrap(or: Abort(.notFound))
    }
update
    func updateHandler(_ req: Request) throws -> EventLoopFuture {
        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 {
        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.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 搜索即可~


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/993261.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存