diff --git a/zio-http/src/main/scala/zio/http/Middleware.scala b/zio-http/src/main/scala/zio/http/Middleware.scala index 335281b09f..a6daeec390 100644 --- a/zio-http/src/main/scala/zio/http/Middleware.scala +++ b/zio-http/src/main/scala/zio/http/Middleware.scala @@ -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))) + } } diff --git a/zio-http/src/main/scala/zio/http/Request.scala b/zio-http/src/main/scala/zio/http/Request.scala index 397ccf87a9..8cc9ccfe09 100644 --- a/zio-http/src/main/scala/zio/http/Request.scala +++ b/zio-http/src/main/scala/zio/http/Request.scala @@ -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 { diff --git a/zio-http/src/main/scala/zio/http/Response.scala b/zio-http/src/main/scala/zio/http/Response.scala index 75c33ed68b..4a630f4d54 100644 --- a/zio-http/src/main/scala/zio/http/Response.scala +++ b/zio-http/src/main/scala/zio/http/Response.scala @@ -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.