Skip to content

Commit

Permalink
add flash scope
Browse files Browse the repository at this point in the history
  • Loading branch information
TomTriple committed Sep 19, 2023
1 parent 8780eb9 commit 54ed9e9
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
7 changes: 7 additions & 0 deletions zio-http/src/main/scala/zio/http/Middleware.scala
Original file line number Diff line number Diff line change
Expand Up @@ -243,4 +243,11 @@ object Middleware extends HandlerAspects {
)
}
}

/**
* Creates a middleware for managing the flash scope.
*/
def flashScopeHandling: HandlerAspect[Any, Unit] = Middleware.intercept { (req, resp) =>
req.cookie("zio-http-flash").fold(resp)(flash => resp.addCookie(Cookie.clear(flash.name)))
}
}
7 changes: 7 additions & 0 deletions zio-http/src/main/scala/zio/http/Request.scala
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ final case class Request(
*/
def unnest(prefix: Path): Request =
copy(url = self.url.copy(path = self.url.path.unnest(prefix)))

def cookie(name: String): Option[Cookie] =
header(Header.Cookie).map(_.value).flatMap(_.filter(_.name == name).headOption)

def flashMessage: Option[String] =
cookie("zio-http-flash").map(_.content)

}

object Request {
Expand Down
3 changes: 3 additions & 0 deletions zio-http/src/main/scala/zio/http/Response.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ final case class Response(
def addCookie(cookie: Cookie.Response): Response =
self.copy(headers = self.headers ++ Headers(Header.SetCookie(cookie)))

def addFlashMessage(message: String): Response =
addCookie(Cookie.Response("zio-http-flash", message))

/**
* Collects the potentially streaming body of the response into a single
* chunk.
Expand Down

0 comments on commit 54ed9e9

Please sign in to comment.