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

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

The newest version!
package io.hireproof.structure

import cats.data.{Chain, Validated}
import cats.syntax.all._
import cats.{Eval, Invariant}
import io.hireproof.screening.Validation

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

  override def zipAll[T](queries: Queries[T]): Queries[A |*| T] = toQueries zipAll queries
  override def zip[T](query: Query[T]): Queries[A |*| T] = toQueries zip query

  def mapSchema[T](f: Schema[A] => Schema[T]): Query[T] = copy(schema = schema.map(f))
  def toQueries: Queries[A] = Queries.fromQuery(this)

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

  def fromStringChain(queries: Chain[(String, String)]): Validated[Errors, (Chain[(String, String)], A)] =
    collectAndRemoveFirst(queries) { case (`name`, value) => value }.traverse(schema.value.fromString)

  def toStringChain(a: A): Chain[(String, String)] = Chain.fromOption(schema.value.toString(a).tupleLeft(name))
}

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

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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy