com-lihaoyi / cask

Cask: a Scala HTTP micro-framework. Cask makes it easy to set up a website, backend server, or REST API using Scala
https://com-lihaoyi.github.io/cask/
Other
525 stars 55 forks source link

cask.Endpoint for Jackson #121

Open gabrieljones opened 5 months ago

gabrieljones commented 5 months ago

I attempted to create my own cask.Endpoint using Jackson, but I got lost quickly. I was able to create a @getJackson() equivalent to @cask.getJson(). But @putJackson() eludes me. Please help.

Here is my getJackson()

trait JacksonData extends Response.Data
object JacksonData extends DataCompanion[JacksonData]{
  val (reader: ObjectReader, writer: ObjectWriter, mapper: JsonMapper) = buildReaderWriterMapper
  implicit class JacksonDataImpl(t: JsonNode) extends JacksonData {
    def headers: Seq[(String, String)] = Seq("Content-Type" -> "application/json")
    def write(out: OutputStream): Unit = {
      writer.writeValue(out, t)
      out.flush()
    }
  }
}

class getJackson(val path: String, override val subpath: Boolean = false)
  extends HttpEndpoint[Response[JacksonData], Seq[String]]{
  val methods: Seq[String] = Seq("get")
  type InputParser[T] = QueryParamReader[T]
  def wrapFunction(ctx: Request, delegate: Delegate): Result[Response.Raw] = {
    delegate(WebEndpoint.buildMapFromQueryParams(ctx))
  }
  def wrapPathSegment(s: String): Seq[String] = Seq(s)
}
  def buildReaderWriterMapper: (ObjectReader, ObjectWriter, JsonMapper) = {
    val mapper = JsonMapper.builder()
      .addModule(new JavaTimeModule())
      .addModule(DefaultScalaModule)
      .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
      .enable(MapperFeature.APPLY_DEFAULT_VALUES)
      .build()
    (mapper.reader, mapper.writer, mapper)
  }