2

I have the following snippet using multi part file uploads. One of the parts reads as byte while the other reads string. One that reads as Byte shows the correct size while the one reading as String reads only one line. What am I missing ?

  val routes = HttpRoutes.of[IO] {
    case GET -> Root                     => Ok(html.index())
    case req @ POST -> Root / "generate" =>
      req.decode[Multipart[IO]] { m =>
        m.parts.find(_.name == Some("template")) match {
          case None               => BadRequest("Missing template file")
          case Some(templatePart) => {
            val templateByteStream = for {
              byte <- templatePart.body
            } yield byte

            m.parts.find(_.name == Some("data")) match {
              case Some(datapart) =>
                val dataLineStream = for {
                  line <- datapart.body.through(utf8.decode)
                } yield line

                Ok {
                  for {
                    templateBytes <- templateByteStream.compile.toList
                    datalines     <- dataLineStream.compile.toList
                    templateSize  = templateBytes.size
                    dataLineCount = datalines.size
                  } yield s"template size $templateSize && dataline count $dataLineCount"
                }
              case None => BadRequest("Missing data file")
            }
          }
        }
      }
  }
nashter
  • 1,181
  • 1
  • 15
  • 33
  • Because you are reading the whole data as a single string, maybe you also wanted to `through(text.lines)` to split the text by lines? - BTW, those `for` are completely unnecessary and redundant. – Luis Miguel Mejía Suárez Jul 21 '22 at 20:56
  • That works. Thanks Luis. Those `for` were to myself clear. Still in learning phase. Such suggestions from community definitely helps in learning. I – nashter Jul 21 '22 at 22:00

1 Answers1

0

Solution:

Because you are reading the whole data as a single string, maybe you also wanted to through(text.lines)

Credits: "Luis Miguel Mejía Suárez"

nashter
  • 1,181
  • 1
  • 15
  • 33