All Downloads are FREE. Search and download functionalities are using the official Maven repository.

sttp.model.Part.scala Maven / Gradle / Ivy

There is a newer version: 2.0.0-RC4
Show newest version
package sttp.model

import Part._

case class Part[T](
    name: String,
    body: T,
    otherDispositionParams: Map[String, String],
    headers: Seq[Header]
) {
  def dispositionParam(k: String, v: String): Part[T] = copy(otherDispositionParams = otherDispositionParams + (k -> v))

  def fileName(v: String): Part[T] = dispositionParam(FileNameDispositionParam, v)
  def fileName: Option[String] = otherDispositionParams.get(FileNameDispositionParam)

  def contentType(v: String): Part[T] = header(Header(HeaderNames.ContentType, v))
  def contentType: Option[String] = header(HeaderNames.ContentType)

  def header(h: Header): Part[T] = copy(headers = headers :+ h)
  def header(k: String, v: String): Part[T] = header(Header(k, v))

  def header(k: String): Option[String] = headers.find(_.name == k).map(_.value)

  def contentDispositionHeaderValue: String = {
    def encode(s: String): String = new String(s.getBytes("utf-8"), "iso-8859-1")
    "form-data; " + dispositionParams.map { case (k, v) => s"$k=${encode(v)}" }.mkString("; ")
  }

  def dispositionParams: Map[String, String] = otherDispositionParams + (NameDispositionParam -> name)
}

object Part {
  def apply[T](
      name: String,
      body: T,
      contentType: Option[String] = None,
      fileName: Option[String] = None,
      otherDispositionParams: Map[String, String] = Map.empty,
      otherHeaders: Seq[Header] = Nil
  ): Part[T] = {
    val p1 = Part(name, body, otherDispositionParams, otherHeaders)
    val p2 = contentType.map(p1.contentType).getOrElse(p1)
    fileName.map(p2.fileName).getOrElse(p2)
  }

  val NameDispositionParam = "name"
  val FileNameDispositionParam = "filename"
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy