Skip to content

Commit

Permalink
Document decorator returning a response
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielMiddleton committed May 17, 2024
1 parent 1b13abc commit 5781ef9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
25 changes: 23 additions & 2 deletions example/decorated/app/src/Decorated.scala
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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) = {
Expand All @@ -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")
Expand Down
3 changes: 2 additions & 1 deletion example/decorated/app/test/src/ExampleTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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"
}
}
}

0 comments on commit 5781ef9

Please sign in to comment.