LoginSignup
2
1

More than 5 years have passed since last update.

Vapor 3.0 でのルーティングでリダイレクト or ビューのレンダリングをする (2)

Last updated at Posted at 2018-05-13

例えば、

  • ログインしていればビューをレンダリング
  • ログインしていなければログインページにリダイレクト

をしたい場合を考える。

Vapor 3.0 でのルーティングでリダイレクト or ビューのレンダリングをする (1) では、型安全な戻り値を返すために2種類の別の型のレスポンスをラップした Enum を用意する方法を紹介した。

しかし、もっと手軽に実現したい場合は、AnyResponse を利用することができる。

例えば、上記記事と同様のことを AnyResponse を使うと↓のように書ける。

final class ArticleController {

    ...

    func new(_ req: Request) throws -> Future<AnyResponse> {
        guard isLoggedIn(req) else {
            let redirect = req.redirect(to: "/users/login")
            return Future.map(on: req) { AnyResponse(redirect) }
        }
        let page = try req.view().render("articles/new")
        return Future.map(on: req) { AnyResponse(page) }
    }

    ...

}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1