scalapattern-matchinghttp4s

Pattern type is incompatible with expected type?


I am trying to create a post endpoint for a particular route but am getting the error message

Pattern type is incompatible with expected type found ContextRequest[F,A], required: Request[F]

    case _ @ POST -> Root / "batch-notify" as _ =>
      handler.handle("create.notifications.batchNotify") {
        for {
          _ <- log.info("Running batch notification job") *> Sync[F].pure(())
          r <- batchingService.createNotifications.flatMap(_ => Ok())
        } yield r
      }.fireAndForget.flatMap(_ => Accepted())

I'm quite new to Scala and have tried fixing it but getting nowhere, would anyone be able to help?


Solution

  • _ @ POST -> Root / "batch-notify" as _
    

    aka

    POST -> Root / "batch-notify" as _ 
    

    aka

    POST -> Root / "batch-notify" as user
    

    is an AuthedRequest used for AuthedRoutes

    https://http4s.org/v1/docs/auth.html

    If you put it into a pattern matching where Request is expected for HttpRoutes (i.e. without authentication)

    https://http4s.org/v1/docs/service.html

    then you'll have a compile error

    pattern type is incompatible with expected type;
     found   : org.http4s.AuthedRequest[F,A]
        (which expands to)  org.http4s.ContextRequest[F,A]
     required: org.http4s.Request[F]
    

    You can find example how to combine AuthedRoutes with HttpRoutes at https://http4s.org/v1/docs/auth.html#composing-authenticated-routes

    val spanishRoutes: AuthedRoutes[User, IO] =
        AuthedRoutes.of {
            case GET -> Root / "hola" as user => Ok(s"Hola, ${user.name}")
        }
    
    val frenchRoutes: HttpRoutes[IO] =
        HttpRoutes.of {
            case GET -> Root / "bonjour" => Ok(s"Bonjour")
        }
    
    val serviceSpanish: HttpRoutes[IO] =
      middleware(spanishRoutes) <+> frenchRoutes