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

io.hireproof.structure.Field.scala Maven / Gradle / Ivy

The newest version!
package io.hireproof.structure

import cats.data.Validated
import cats.{Eval, Invariant}
import io.circe.JsonObject
import io.hireproof.screening.Validation

final case class Field[A](name: String, schema: Eval[Schema[A]]) extends Structure.Product[A] {
  override type Self[a] = Field[a]
  override type Element[a] = Field[a]
  override type Group[a] = Schema.Product[a]

  override def zipAll[T](schema: Schema.Product[T]): Schema.Product[A |*| T] = toProduct.zipAll(schema)
  override def zip[T](field: Field[T]): Schema.Product[A |*| T] = toProduct.zip(field)

  def toProduct: Schema.Product[A] = Schema.Product.fromField(this)

  override private[structure] def vimap[T](
      f: A => Validated[Errors, T],
      g: T => A,
      validation: Option[Validation[_, _]]
  ): Field[T] = copy(schema = schema.map(_.vimap(f, g, validation)))

  def fromJsonObject(json: JsonObject): Validated[Errors, (JsonObject, A)] =
    schema.value.fromJson(json(name)).leftMap(_.modifyHistory(name /: _)).map((json.remove(name), _))

  def toJsonObject(a: A): JsonObject =
    schema.value.toJson(a).fold(JsonObject.empty)(JsonObject.singleton(name, _))
}

object Field {
  def default[A](name: String, schema: => Schema[A]): Field[A] = Field(name, Eval.later(schema))

  implicit val invariant: Invariant[Field] = new Invariant[Field] {
    override def imap[A, B](fa: Field[A])(f: A => B)(g: B => A): Field[B] = fa.imap(f)(g)
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy