Skip to content

Commit

Permalink
Merge pull request #357 from lichess-org/refactor-middleware
Browse files Browse the repository at this point in the history
Code golf middleware
  • Loading branch information
lenguyenthanh authored Nov 1, 2024
2 parents fc301b4 + 44d8a24 commit 4726d8a
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 13 deletions.
16 changes: 4 additions & 12 deletions modules/app/src/main/scala/http.middleware.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,18 @@ package app
import cats.effect.IO
import org.http4s.*
import org.http4s.server.middleware.*
import org.typelevel.log4cats.{ Logger, LoggerFactory }
import org.typelevel.log4cats.LoggerFactory

import scala.concurrent.duration.*

type Middleware = HttpRoutes[IO] => HttpRoutes[IO]
def ApplyMiddleware(config: HttpServerConfig)(routes: HttpRoutes[IO])(using
LoggerFactory[IO]
): HttpRoutes[IO] =

val autoSlash: Middleware = AutoSlash(_)
val timeout: Middleware = Timeout(60.seconds)

val middleware = autoSlash.andThen(timeout)
def MkMiddleware(config: HttpServerConfig)(using LoggerFactory[IO]): Middleware =

def verboseLogger =
RequestLogger.httpRoutes[IO](true, true).andThen(ResponseLogger.httpRoutes[IO, Request[IO]](true, true))

given Logger[IO] = LoggerFactory[IO].getLogger
val logger =
if config.apiLogger then verboseLogger
else ApiErrorLogger.instance
else ApiErrorLogger.instance(using LoggerFactory[IO].getLogger)

logger(middleware(routes))
logger.andThen(AutoSlash(_)).andThen(Timeout(60.seconds))
2 changes: 1 addition & 1 deletion modules/app/src/main/scala/http.routes.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ def Routes(resources: AppResources, config: HttpServerConfig)(using
if config.enableDocs then apiRoutes.map(_ <+> docs)
else apiRoutes

allRoutes.map(ApplyMiddleware(config))
allRoutes.map(MkMiddleware(config))

0 comments on commit 4726d8a

Please sign in to comment.