From 5781ef9539383357a22878678da221beab3d473f Mon Sep 17 00:00:00 2001 From: Daniel Middleton Date: Thu, 16 May 2024 12:44:35 -0500 Subject: [PATCH] Document decorator returning a response --- example/decorated/app/src/Decorated.scala | 25 +++++++++++++++++-- .../decorated/app/test/src/ExampleTests.scala | 3 ++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/example/decorated/app/src/Decorated.scala b/example/decorated/app/src/Decorated.scala index cfe41c2867..5347629bb0 100644 --- a/example/decorated/app/src/Decorated.scala +++ b/example/decorated/app/src/Decorated.scala @@ -1,6 +1,6 @@ package app -object Decorated extends cask.MainRoutes{ - class User{ +object Decorated extends cask.MainRoutes { + class User { override def toString = "[haoyi]" } class loggedIn extends cask.RawDecorator { @@ -14,6 +14,21 @@ object Decorated extends cask.MainRoutes{ } } + class withCustomHeader extends cask.RawDecorator { + def wrapFunction(request: cask.Request, delegate: Delegate) = { + request.headers.get("x-custom-header").map(_.head) match { + case Some(header) => delegate(Map("customHeader" -> header)) + case None => + cask.router.Result.Success( + cask.model.Response( + s"Request is missing required header: 'X-CUSTOM-HEADER'", + 400 + ) + ) + } + } + } + @withExtra() @cask.get("/hello/:world") def hello(world: String)(extra: Int) = { @@ -26,6 +41,12 @@ object Decorated extends cask.MainRoutes{ world + user } + @withCustomHeader() + @cask.get("/echo") + def echoHeader(request: cask.Request)(customHeader: String) = { + customHeader + } + @withExtra() @loggedIn() @cask.get("/internal-extra/:world") diff --git a/example/decorated/app/test/src/ExampleTests.scala b/example/decorated/app/test/src/ExampleTests.scala index 65379ce4aa..09fdf1cd12 100644 --- a/example/decorated/app/test/src/ExampleTests.scala +++ b/example/decorated/app/test/src/ExampleTests.scala @@ -3,7 +3,7 @@ import io.undertow.Undertow import utest._ -object ExampleTests extends TestSuite{ +object ExampleTests extends TestSuite { def withServer[T](example: cask.main.Main)(f: String => T): T = { val server = Undertow.builder .addHttpListener(8081, "localhost") @@ -24,6 +24,7 @@ object ExampleTests extends TestSuite{ requests.get(s"$host/internal-extra/goo").text() ==> "goo[haoyi]31337" requests.get(s"$host/hello-default?world=worldz").text() ==> "worldz[haoyi]" requests.get(s"$host/hello-default").text() ==> "world[haoyi]" + requests.get(s"$host/echo", headers = Map("X-CUSTOM-HEADER" -> "header")).text() ==> "header" } } }