SerializeResponseCallback.kt

  1. package com.hexagontk.rest

  2. import com.hexagontk.http.handlers.HttpCallback
  3. import com.hexagontk.http.handlers.HttpContext
  4. import com.hexagontk.serialization.SerializationManager
  5. import com.hexagontk.serialization.serialize

  6. // TODO Create SerializeResponseHandler like CorsHandler
  7. class SerializeResponseCallback: HttpCallback {

  8.     init {
  9.         check(SerializationManager.formats.isNotEmpty()) {
  10.             "Serialization callbacks require at least one registered format"
  11.         }
  12.     }

  13.     override fun invoke(context: HttpContext): HttpContext {
  14.         val responseBody = context.response.body

  15.         if (responseBody is String || responseBody is ByteArray)
  16.             return context

  17.         return (context.request.accept - anyContentType)
  18.             .ifEmpty { context.response.contentType?.let(::listOf) ?: emptyList() }
  19.             .associateWith { SerializationManager.formatOfOrNull(it.mediaType) }
  20.             .mapNotNull { (k, v) -> v?.let { k to it } }
  21.             .firstOrNull()
  22.             ?.let { (ct, sf) -> ct to responseBody.serialize(sf) }
  23.             ?.let { (ct, c) -> context.send(body = c, contentType = ct) }
  24.             ?: context
  25.     }
  26. }