Vapor系列教程 - Middleware

Swift國內社區: SwiftMic


Middleware 是現代 Web 框架中必不可少的一部分。通過 Middleware 可以單獨處理 Request 和 Response,極其方便。

Middleware

基本用法


SampleMiddleware.swift

import Vapor
import HTTP

class SampleMiddleware: Middleware {

    func respond(to request: Request, chainingTo chain: Responder) throws -> Response {
        // You can manipulate the request before calling the handler
        // and abort early if necessary, a good injection point for
        // handling auth.

        // 此處可統一處理 Request 請求

        let response = try chain.respond(to: request)

        // 此處可統一處理 Response 響應

        // You can also manipulate the response to add headers
        // cookies, etc.

        return response

        // Vapor Middleware is based on S4 Middleware.
        // This means you can share it with any other project
        // that uses S4 Middleware. 
    }

}

main.swift

drop.middleware.append(SampleMiddleware())

每次 Request 和 Response 都將會響應到 SampleMiddleware 中的 respond 方法。

示例1


如果想給所有 API 的 Response 增加一個版本號字段,可直接在 SampleMiddleware 中添加代碼: response.headers["Api_Version"] = "v1" 即可,而無需在每個 Response 中進行設置。

import Vapor
import HTTP

class SampleMiddleware: Middleware {

    func respond(to request: Request, chainingTo chain: Responder) throws -> Response {
        
        let response = try chain.respond(to: request)

        response.headers["Api_Version"] = "v1"

        return response
    }

}

示例2


有些 API 需要登錄后才能調用,這里涉及到用戶鑒權的問題,可通過 Middleware 統一處理 token 異常情況,而無需在每個 Response 中處理。

定義異常類型

enum ZException: Error {
    case ERROR_AUTH_TOKEN_INVALID
}

ERROR_AUTH_TOKEN_INVALID 異常類型統一處理

import Vapor
import HTTP

class SampleMiddleware: Middleware {

    func respond(to request: Request, chainingTo chain: Responder) throws -> Response {
        do {
            return try chain.respond(to: request)
        } catch ZException.ERROR_AUTH_TOKEN_INVALID {
            throw Abort.custom(status: .unauthorized, message: "ERROR_AUTH_TOKEN_INVALID")
        }
    }

}

當檢測到 token 無效時,只需要拋出 ERROR_AUTH_TOKEN_INVALID 異常即可。

throw ZException.ERROR_AUTH_TOKEN_INVALID

Go to Vapor系列教程 - 目錄

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • Refer to: www.threemeal.com/blog/12/ 中間件 中間件是一個鉤子框架,它們可以介...
    蘭山小亭閱讀 16,580評論 9 165
  • 注意:更新iOS 9.3, and Swift 2.2- 2016年4月2日 原文https://www.rayw...
    Tippi閱讀 4,388評論 0 2
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,255評論 4 61
  • scrapy學習筆記(有示例版) 我的博客 scrapy學習筆記1.使用scrapy1.1創建工程1.2創建爬蟲模...
    陳思煜閱讀 12,785評論 4 46