Skip to content

Commit

Permalink
refactor: Replace spray json with zio-json
Browse files Browse the repository at this point in the history
  • Loading branch information
seakayone committed Nov 16, 2023
1 parent f11dfef commit c1939f9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@

package org.knora.webapi.store.iiif.api

import org.apache.pekko.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.DefaultJsonProtocol
import spray.json.RootJsonFormat
import zio.*
import zio.json.DeriveJsonDecoder
import zio.json.JsonDecoder
import zio.macros.accessible
import zio.nio.file.Path

Expand Down Expand Up @@ -48,10 +47,15 @@ case class FileMetadataSipiResponse(
}
}

object FileMetadataSipiResponse extends SprayJsonSupport with DefaultJsonProtocol {
implicit val sipiKnoraJsonResponseFormat: RootJsonFormat[FileMetadataSipiResponse] = jsonFormat8(
FileMetadataSipiResponse.apply
)
object FileMetadataSipiResponse {
// Because Sipi returns JSON Numbers which are whole numbers but not a valid Scala Int, e.g. `width: 1920.0`, we need to
// use a custom decoder for Int. See also https://github.com/zio/zio-json/issues/1049#issuecomment-1814108354
implicit val anyWholeNumber: JsonDecoder[Int] = JsonDecoder[Double].mapOrFail { d =>
val i = d.toInt
if (d == i.toDouble) { Right(i) }
else { Left("32-bit int expected") }
}
implicit val decoder: JsonDecoder[FileMetadataSipiResponse] = DeriveJsonDecoder.gen[FileMetadataSipiResponse]
}

@accessible
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
import spray.json.*
import zio.*
import zio.json.DecoderOps
import zio.nio.file.Path

import java.net.URI
Expand Down Expand Up @@ -73,7 +74,11 @@ final case class SipiServiceLive(
*/
override def getFileMetadata(filePath: String): Task[FileMetadataSipiResponse] =
doSipiRequest(new HttpGet(sipiConfig.internalBaseUrl + filePath + "/knora.json"))
.mapAttempt(_.parseJson.convertTo[FileMetadataSipiResponse])
.flatMap(it =>
ZIO
.fromEither(it.fromJson[FileMetadataSipiResponse])
.mapError(e => SipiException(s"Invalid response from Sipi: $e, $it"))
)

/**
* Asks Sipi to move a file from temporary storage to permanent storage.
Expand Down

0 comments on commit c1939f9

Please sign in to comment.