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

Add Run Before #840

Merged
merged 3 commits into from
Jan 15, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions zio-http/src/main/scala/zhttp/http/Middleware.scala
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ sealed trait Middleware[-R, +E, +AIn, -BIn, -AOut, +BOut] { self =>
final def runAfter[R1 <: R, E1 >: E](effect: ZIO[R1, E1, Any]): Middleware[R1, E1, AIn, BIn, AOut, BOut] =
self.mapZIO(bOut => effect.as(bOut))

final def runBefore[R1 <: R, E1 >: E](effect: ZIO[R1, E1, Any]): Middleware[R1, E1, AIn, BIn, AOut, BOut] =
self.contramapZIO(b => effect.as(b))

/**
* Applies Middleware based only if the condition function evaluates to true
*/
Expand Down
16 changes: 13 additions & 3 deletions zio-http/src/test/scala/zhttp/http/MiddlewareSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,20 @@ object MiddlewareSpec extends DefaultRunnableSpec with HExitAssertion {
val app = Http.identity[Int] @@ mid
assertM(app(0))(equalTo(3))
} +
testM("runBefore") {
val mid = Middleware.identity.runBefore(console.putStrLn("A"))
val app = Http.fromZIO(console.putStrLn("B")) @@ mid
assertM(app(()) *> TestConsole.output)(equalTo(Vector("A\n", "B\n")))
} +
testM("runAfter") {
val mid = Middleware.succeed(1).runAfter(console.putStrLn("A"))
val app = Http.succeed(1) @@ mid
assertM(app(()) *> TestConsole.output)(equalTo(Vector("A\n")))
val mid = Middleware.identity.runAfter(console.putStrLn("B"))
val app = Http.fromZIO(console.putStrLn("A")) @@ mid
assertM(app(()) *> TestConsole.output)(equalTo(Vector("A\n", "B\n")))
} +
testM("runBefore and runAfter") {
val mid = Middleware.identity.runBefore(console.putStrLn("A")).runAfter(console.putStrLn("C"))
val app = Http.fromZIO(console.putStrLn("B")) @@ mid
assertM(app(()) *> TestConsole.output)(equalTo(Vector("A\n", "B\n", "C\n")))
} +
testM("race") {
val mid = Middleware.succeed('A').delay(2 second) race Middleware.succeed("B").delay(1 second)
Expand Down