Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added cookie helpers #2439

Merged
merged 7 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion docs/dsl/cookies.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,21 @@ It updates the response header `Set-Cookie` as ```Set-Cookie: <cookie-name>=<coo

## Getting Cookie from Request

In HTTP requests, cookies are stored in the `cookie` header. `cookiesDecoded` can be used to get all the cookies in the request:
From HTTP requests, a single cookie can be retrieved with `cookie`.

```scala mdoc
private val app4 =
Routes(
Method.GET / "cookie" -> handler { (req: Request) =>
val cookieContent = req.cookie("sessionId").map(_.content)
Response.text(s"cookie content: $cookieContent")
}
)
```

## Getting Cookie from Header

In HTTP requests, cookies are stored in the `cookie` header.

```scala mdoc
private val app3 =
Expand Down
52 changes: 22 additions & 30 deletions zio-http/src/main/scala/zio/http/Header.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2491,14 +2491,11 @@ object Header {
val type1 = RichTextCodec.string.collectOrFail("unsupported main type") {
case value if MediaType.mainTypeMap.get(value).isDefined => value
}
val type1x = (RichTextCodec.literalCI("x-") ~ token.repeat.string).transform[String](in => s"${in._1}${in._2}", in => ("x-", s"${in.substring(2)}"))
val codecType1 = (type1 | type1x).transform[String](
_.merge,
{
case x if x.startsWith("x-") => Right(x)
case x => Left(x)
},
)
val type1x = (RichTextCodec.literalCI("x-") ~ token.repeat.string).transform[String](in => s"${in._1}${in._2}")(in => ("x-", s"${in.substring(2)}"))
val codecType1 = (type1 | type1x).transform[String](_.merge) {
case x if x.startsWith("x-") => Right(x)
case x => Left(x)
}
val codecType2 = token.repeat.string
val codecType = (codecType1 <~ RichTextCodec.char('/').const('/')) ~ codecType2
val attribute = token.repeat.string
Expand All @@ -2508,32 +2505,27 @@ object Header {

val param = ((
RichTextCodec.char(';').const(';') ~>
(RichTextCodec.whitespaceChar.repeat | RichTextCodec.empty).transform[Char](_ => ' ', _ => Left(Chunk(()))).const(' ') ~>
(RichTextCodec.whitespaceChar.repeat | RichTextCodec.empty).transform[Char](_ => ' ')(_ => Left(Chunk(()))).const(' ') ~>
attribute <~
RichTextCodec.char('=').const('=')
) ~ value)
.transformOrFailLeft[ContentType.Parameter](
in => ContentType.Parameter.fromCodec(in),
in => in.toCodec,
)
.transformOrFailLeft[ContentType.Parameter](in => ContentType.Parameter.fromCodec(in))(in => in.toCodec)
val params = param.repeat
(codecType ~ params).transform[ContentType](
{ case (mainType, subType, params) =>
ContentType(
MediaType.forContentType(s"$mainType/$subType").get,
params.collect { case p if p.key == ContentType.Parameter.Boundary.name => zio.http.Boundary(p.value) }.headOption,
params.collect { case p if p.key == ContentType.Parameter.Charset.name => java.nio.charset.Charset.forName(p.value) }.headOption,
)
},
in =>
(
in.mediaType.mainType,
in.mediaType.subType,
Chunk(
in.charset.map(in => Parameter.Charset(Parameter.Payload(Parameter.Charset.name, in, false))),
in.boundary.map(in => Parameter.Boundary(Parameter.Payload(Parameter.Boundary.name, in, false))),
).flatten,
),
(codecType ~ params).transform[ContentType] { case (mainType, subType, params) =>
ContentType(
MediaType.forContentType(s"$mainType/$subType").get,
params.collect { case p if p.key == ContentType.Parameter.Boundary.name => zio.http.Boundary(p.value) }.headOption,
params.collect { case p if p.key == ContentType.Parameter.Charset.name => java.nio.charset.Charset.forName(p.value) }.headOption,
)
}(in =>
(
in.mediaType.mainType,
in.mediaType.subType,
Chunk(
in.charset.map(in => Parameter.Charset(Parameter.Payload(Parameter.Charset.name, in, false))),
in.boundary.map(in => Parameter.Boundary(Parameter.Payload(Parameter.Boundary.name, in, false))),
).flatten,
),
)
}

Expand Down
37 changes: 35 additions & 2 deletions zio-http/src/main/scala/zio/http/Request.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ package zio.http
import java.net.InetAddress

import zio.stacktracer.TracingImplicits.disableAutoTrace
import zio.{Trace, ZIO}
import zio.{Chunk, Trace, ZIO}

import zio.http.internal.HeaderOps

Expand Down Expand Up @@ -107,8 +107,41 @@ final case class Request(
def unnest(prefix: Path): Request =
copy(url = self.url.copy(path = self.url.path.unnest(prefix)))

/**
* Returns the cookie with the given name if it exists.
*/
def cookie(name: String): Option[Cookie] =
header(Header.Cookie).map(_.value).flatMap(_.filter(_.name == name).headOption)
cookies.find(_.name == name)

/**
* Uses the cookie with the given name if it exists and runs `f` afterwards.
*/
def cookieWithZIO[R, A](name: String)(f: Cookie => ZIO[R, Throwable, A])(implicit
trace: Trace,
): ZIO[R, Throwable, A] =
cookieWithOrFailImpl(name)(identity)(f)

/**
* Uses the cookie with the given name if it exists and runs `f` afterwards.
*
* Also, you can replace a `NoSuchElementException` from an absent cookie with
* `E`.
*/
def cookieWithOrFail[R, E, A](name: String)(missingCookieError: E)(f: Cookie => ZIO[R, E, A])(implicit
trace: Trace,
): ZIO[R, E, A] =
cookieWithOrFailImpl(name)(_ => missingCookieError)(f)

private def cookieWithOrFailImpl[R, E, A](name: String)(e: Throwable => E)(f: Cookie => ZIO[R, E, A])(implicit
trace: Trace,
): ZIO[R, E, A] =
ZIO.getOrFailWith(e(new java.util.NoSuchElementException(s"cookie doesn't exist: $name")))(cookie(name)).flatMap(f)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will create an exception with stacktrace just to be thrown away immediately. This does not seem to be efficient.
I'd change it just simply to

Suggested change
ZIO.getOrFailWith(e(new java.util.NoSuchElementException(s"cookie doesn't exist: $name")))(cookie(name)).flatMap(f)
cookie(name) match {
case Some(cookie) => f(e)
case None => ZIO.fail(e)
}

where e is not a function

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added your suggestions, thank you!


/**
* Returns all cookies from the request.
*/
def cookies: Chunk[Cookie] =
header(Header.Cookie).fold(Chunk.empty[Cookie])(_.value.toChunk)

def flashMessage: Option[String] =
cookie("zio-http-flash").map(_.content)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import zio.{Chunk, NonEmptyChunk}
sealed trait RichTextCodec[A] { self =>

final def string(implicit ev: A =:= Chunk[Char]): RichTextCodec[String] =
self.asType[Chunk[Char]].transform(_.mkString, a => Chunk(a.toList: _*))
self.asType[Chunk[Char]].transform(_.mkString)(a => Chunk(a.toList: _*))

/**
* Returns a new codec that is the sequential composition of this codec and
Expand Down
Loading