Rest.kt

  1. package com.hexagonkt.rest

  2. import com.hexagonkt.core.media.*
  3. import com.hexagonkt.http.model.ContentType
  4. import com.hexagonkt.http.model.HttpBase
  5. import com.hexagonkt.serialization.*

  6. val anyContentType = ContentType(ANY_MEDIA)
  7. val textContentType = ContentType(TEXT_PLAIN)
  8. val jsonContentType = ContentType(APPLICATION_JSON)
  9. val yamlContentType = ContentType(APPLICATION_YAML)
  10. val xmlContentType = ContentType(APPLICATION_XML)
  11. val tomlContentType = ContentType(APPLICATION_TOML)
  12. val csvContentType = ContentType(TEXT_CSV)

  13. fun HttpBase.bodyList(): List<*> =
  14.     bodyString().parseList(mediaType())

  15. fun HttpBase.bodyMap(): Map<String, *> =
  16.     bodyString().parseMap(mediaType())

  17. fun HttpBase.bodyMaps(): List<Map<String, *>> =
  18.     bodyString().parseMaps(mediaType())

  19. fun <T> HttpBase.bodyObjects(converter: (Map<String, *>) -> T): List<T> =
  20.     bodyMaps().map(converter)

  21. fun <T> HttpBase.bodyObject(converter: (Map<String, *>) -> T): T =
  22.     bodyMap().let(converter)

  23. fun HttpBase.serializeBody(): Any =
  24.     contentType
  25.         ?.mediaType
  26.         ?.let(SerializationManager::formatOfOrNull)
  27.         ?.let { body.serialize(it) }
  28.         ?: body

  29. fun HttpBase.mediaType(): MediaType =
  30.     contentType?.mediaType ?: error("Missing content type")