当前位置: 首页>>代码示例>>Scala>>正文


Scala ValidatedNel类代码示例

本文整理汇总了Scala中cats.data.ValidatedNel的典型用法代码示例。如果您正苦于以下问题:Scala ValidatedNel类的具体用法?Scala ValidatedNel怎么用?Scala ValidatedNel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ValidatedNel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: AssetProcessing

//设置package包名称以及导入依赖的类
package templates

import aws.Interpreter.ErrorsOr
import cats.data.Validated.{Invalid, Valid}
import cats.data.{NonEmptyList, Validated, ValidatedNel}
import com.amazonaws.regions.{Region, Regions}
import com.ovoenergy.comms.model.{Channel, CommManifest}

object AssetProcessing {

  private val assetTemplateReferenceRegex = "(?:'|\")(?: *)(assets)(?:/[^(\"')]+)(?: *)(?:'|\")".r

  case class ProcessedFiles(templateFiles: List[UploadedTemplateFile], assetFiles: List[UploadedTemplateFile])

  def processAssets(region: Regions,
                    assetsS3Bucket: String,
                    commManifest: CommManifest,
                    uploadedFiles: List[UploadedTemplateFile]): ErrorsOr[ProcessedFiles] = {
    import cats.syntax.traverse._
    import cats.instances.list._
    val (assetFiles, nonAssetFiles) = uploadedFiles.partition(_.fileType == Asset)
    val processedTemplateFiles: Validated[NonEmptyList[String], List[UploadedTemplateFile]] = nonAssetFiles
      .traverseU(templateFile => {
        replaceAssetReferences(region, assetsS3Bucket, templateFile.channel, commManifest, templateFile.contents)
          .map(contents => templateFile.copy(contents = contents))
      })
    processedTemplateFiles.map(ProcessedFiles(_, assetFiles)).toEither
  }

  private def replaceAssetReferences(region: Regions,
                                     assetsS3Bucket: String,
                                     channel: Channel,
                                     commManifest: CommManifest,
                                     contents: Array[Byte]): ValidatedNel[String, Array[Byte]] = {
    def replaceReferences(s3Endpoint: String, contentsString: String) = {
      val replacementAssetsPath = s"$s3Endpoint/assets"
      assetTemplateReferenceRegex
        .replaceAllIn(contentsString, m => m.group(0).replaceFirst(m.group(1), replacementAssetsPath))
        .getBytes
    }
    determineS3Endpoint(region, assetsS3Bucket, channel, commManifest).map(replaceReferences(_, new String(contents)))
  }

  private def determineS3Endpoint(region: Regions,
                                  assetsS3Bucket: String,
                                  channel: Channel,
                                  commManifest: CommManifest): ValidatedNel[String, String] = {
    if (!Region.getRegion(region).isServiceSupported("s3")) {
      Invalid(NonEmptyList.of("S3 not supported in region selected"))
    } else if (!Region.getRegion(region).hasHttpsEndpoint("s3")) {
      Invalid(NonEmptyList.of("No https support for s3 in region selected"))
    } else {
      val s3ServiceEndpoint = Region.getRegion(region).getServiceEndpoint("s3")
      Valid(
        s"https://$s3ServiceEndpoint/$assetsS3Bucket/${commManifest.commType.toString.toLowerCase}/${commManifest.name}/${commManifest.version}/${channel.toString.toLowerCase}")
    }
  }
} 
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:59,代码来源:AssetProcessing.scala

示例2: circeEncoder

//设置package包名称以及导入依赖的类
package featherbed

import java.nio.charset.Charset

import cats.data.ValidatedNel
import cats.implicits._
import io.circe._
import io.circe.generic.auto._
import io.circe.parser._
import io.circe.syntax._
import shapeless.Witness

package object circe {

  private val printer = Printer.noSpaces.copy(dropNullKeys = true)

  implicit def circeEncoder[A: Encoder]: content.Encoder[A, Witness.`"application/json"`.T] =
    content.Encoder.of("application/json") {
      (value: A, charset: Charset) => content.Encoder.encodeString(printer.pretty(value.asJson), charset)
    }

  implicit def circeDecoder[A: Decoder]: content.Decoder.Aux[Witness.`"application/json"`.T, A] =
    content.Decoder.of("application/json") {
      response =>
        content.Decoder.decodeString(response).andThen {
          str => (parse(str).toValidated.toValidatedNel: ValidatedNel[Throwable, Json]).andThen {
            json: Json => json.as[A].toValidated.toValidatedNel: ValidatedNel[Throwable, A]
          }
        }
    }

} 
开发者ID:finagle,项目名称:featherbed,代码行数:33,代码来源:package.scala

示例3: Empty

//设置package包名称以及导入依赖的类
package upNorth

import cats.implicits._
import cats.data.ValidatedNel

sealed trait Error
case object Empty extends Error
case class ContainsSwear(swear: String, item: String) extends Error

object Validation {

  private def validateEmpty(item: String): ValidatedNel[Error, String] = {
    if (item.isEmpty) Empty.invalidNel
    else item.valid
  }

  private def validateSwear(item: String): ValidatedNel[Error, String] = {
    if (item.contains("darn")) ContainsSwear("darn", item).invalidNel
    else item.valid
  }

  def validateItem(item: String): ValidatedNel[Error, String] =
    (validateEmpty(item) |@| validateSwear(item)).tupled.map(_._1)

} 
开发者ID:LukaJCB,项目名称:ScalaUpNorth,代码行数:26,代码来源:Validation.scala

示例4: jsonDecodedStringDecoder

//设置package包名称以及导入依赖的类
package freecli
package circe

import scala.io.Source

import cats.Show
import cats.syntax.show._
import cats.data.{NonEmptyList, Validated, ValidatedNel}
import io.circe.{Decoder, Json}
import io.circe.parser.parse

import core.api.{StringDecoder, StringDecoderError}

trait Instances {
  implicit def jsonDecodedStringDecoder[T](
    implicit ev: StringDecoder[Json],
    show: Show[T],
    decoder: Decoder[T]):
    StringDecoder[T] = {

    new StringDecoder[T] {
      def apply(value: String): ValidatedNel[StringDecoderError, T] = {
        ev(value) match {
          case Validated.Valid(j) =>
            Validated.fromEither(j.as[T]).leftMap(
              f => NonEmptyList.of(StringDecoderError(f.message)))

          case Validated.Invalid(e) => Validated.Invalid(e)
        }
      }

      def toString(v: T): String = {
        v.show
      }
    }
  }

  implicit def jsonStringDecoder: StringDecoder[Json] = {
    new StringDecoder[Json] {
      def apply(value: String): ValidatedNel[StringDecoderError, Json] = {

        val stringToParse =
          if (value.matches(".+\\.json")) {
            Source.fromFile(value).mkString
          } else value

        parse(stringToParse) match {
          case Right(j) =>
            Validated.valid(j)

          case Left(e) => Validated.invalidNel(StringDecoderError(e.message))
        }
      }

      def toString(v: Json): String = {
        v.spaces2
      }
    }
  }
} 
开发者ID:pavlosgi,项目名称:freecli,代码行数:61,代码来源:Instances.scala

示例5: Decoder

//设置package包名称以及导入依赖的类
package freecli
package examples
package decoder

import cats.data.{Validated, ValidatedNel}

import freecli.argument.all._
import freecli.core.api.{StringDecoder, StringDecoderError}

object Decoder extends App {
  sealed trait Fruit
  case object Apple extends Fruit
  case object Pear extends Fruit
  case object Orange extends Fruit

  implicit object fruitStringDecoder extends StringDecoder[Fruit] {
    override def apply(value: String): ValidatedNel[StringDecoderError, Fruit] = {
      value match {
        case v if v.equalsIgnoreCase("Apple") => Validated.valid(Apple)
        case v if v.equalsIgnoreCase("Pear") => Validated.valid(Pear)
        case v if v.equalsIgnoreCase("Orange") => Validated.valid(Orange)
        case v =>
          Validated.invalidNel(StringDecoderError(
            s"$v did not match any of (Apple, Pear, Orange)"))
      }
    }

    override def toString(v: Fruit): String = {
      v match {
        case Apple => "Apple"
        case Pear => "Pear"
        case Orange => "Orange"
      }
    }
  }

  val res = runArgumentOrFail(arg[Fruit])(args)
  println(res)
} 
开发者ID:pavlosgi,项目名称:freecli,代码行数:40,代码来源:Decoder.scala

示例6: Validations

//设置package包名称以及导入依赖的类
package com.wunder.pets.validations

import cats.data
import cats.data.{NonEmptyList, ValidatedNel}
import eu.timepit.refined.api.Validate
import eu.timepit.refined.refineV
import org.postgresql.util.PSQLException

object Validations {
  type Validated[T] = ValidatedNel[ValidationError, T]
  type Errors = NonEmptyList[ValidationError]
  type ErrorMessages = Seq[String]
  type WithErrorMessages[T] = Either[ErrorMessages, T]

  def validate[VALUE, VALIDATION](v: VALUE, e: ValidationError)
                                 (implicit validation: Validate[VALUE, VALIDATION]): Validated[VALUE] = {
    val validated: Either[Errors, VALUE] = refineV[VALIDATION](v)
      .left.map(_ => NonEmptyList(e, Nil))
      .right.map(_.value)
    data.Validated.fromEither(validated)
  }

  def assureUnique[T]: PartialFunction[Throwable, WithErrorMessages[T]] = {
    case e: PSQLException => {
      toErrorMessages(dbError(e))
    }
  }

  def dbError(e: PSQLException): Errors = {
    def isUniquenessViolation(e: PSQLException) = e.getServerErrorMessage.getDetail.matches(".* already exists.")

    val error = if (isUniquenessViolation(e)) {
      new DuplicateValue(e)
    } else {
      new GeneralError(e.getMessage)
    }
    NonEmptyList(error, Nil)
  }

  def toErrorMessages[T](errors: Errors): WithErrorMessages[T] = Left(errors.map(_.message).toList)
} 
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:42,代码来源:Validations.scala

示例7: parse

//设置package包名称以及导入依赖的类
package io.circe.jackson

import cats.data.ValidatedNel
import io.circe.{ Decoder, Error, Json, Parser, ParsingFailure }
import java.io.File
import scala.util.control.NonFatal

trait JacksonParser extends Parser { this: WithJacksonMapper =>
  final def parse(input: String): Either[ParsingFailure, Json] = try {
    Right(mapper.readValue(jsonStringParser(input), classOf[Json]))
  } catch {
    case NonFatal(error) => Left(ParsingFailure(error.getMessage, error))
  }

  final def parseFile(file: File): Either[ParsingFailure, Json] = try {
    Right(mapper.readValue(jsonFileParser(file), classOf[Json]))
  } catch {
    case NonFatal(error) => Left(ParsingFailure(error.getMessage, error))
  }

  final def parseByteArray(bytes: Array[Byte]): Either[ParsingFailure, Json] = try {
    Right(mapper.readValue(jsonBytesParser(bytes), classOf[Json]))
  } catch {
    case NonFatal(error) => Left(ParsingFailure(error.getMessage, error))
  }

  final def decodeByteArray[A: Decoder](bytes: Array[Byte]): Either[Error, A] =
    finishDecode[A](parseByteArray(bytes))

  final def decodeByteArrayAccumulating[A: Decoder](bytes: Array[Byte]): ValidatedNel[Error, A] =
    finishDecodeAccumulating[A](parseByteArray(bytes))

  final def decodeFile[A: Decoder](file: File): Either[Error, A] =
    finishDecode[A](parseFile(file))

  final def decodeFileAccumulating[A: Decoder](file: File): ValidatedNel[Error, A] =
    finishDecodeAccumulating[A](parseFile(file))
} 
开发者ID:circe,项目名称:circe-jackson,代码行数:39,代码来源:JacksonParser.scala

示例8: Validations

//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.compile

import cats.data.Validated.{invalid, valid}
import cats.data.ValidatedNel
import pl.touk.nussknacker.engine.compile.ProcessCompilationError.{MissingParameters, NodeId, RedundantParameters}

object Validations {

  def validateParameters[T>:PartSubGraphCompilationError](definedParamNames: List[String], usedParamNames: List[String])(implicit nodeId: NodeId)
  : ValidatedNel[T, Unit]= {
    val usedParamNamesSet = usedParamNames.toSet
    val definedParamNamesSet = definedParamNames.toSet
    val redundantParams = usedParamNamesSet.diff(definedParamNamesSet)
    val notUsedParams = definedParamNamesSet.diff(usedParamNamesSet)
    if (redundantParams.nonEmpty) {
      invalid(RedundantParameters(redundantParams)).toValidatedNel
    } else if (notUsedParams.nonEmpty) {
      invalid(MissingParameters(notUsedParams)).toValidatedNel
    } else {
      valid(Unit)
    }
  }

} 
开发者ID:TouK,项目名称:nussknacker,代码行数:25,代码来源:Validations.scala

示例9: ValidationContext

//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.compile

import cats.data.Validated.{Invalid, Valid}
import cats.data.{ValidatedNel, _}
import pl.touk.nussknacker.engine.compile.ProcessCompilationError.{NoParentContext, NodeId, OverwrittenVariable}
import pl.touk.nussknacker.engine.definition.DefinitionExtractor.{ClazzRef, PlainClazzDefinition}

case class ValidationContext(variables: Map[String, ClazzRef] = Map.empty,
                             typesInformation: List[PlainClazzDefinition] = List.empty,
                             parent: Option[ValidationContext] = None) {

  def apply(name: String): ClazzRef =
    get(name).getOrElse(throw new RuntimeException(s"Unknown variable: $name"))

  def get(name: String): Option[ClazzRef] =
    variables.get(name)

  def contains(name: String): Boolean = variables.contains(name)

  def withVariable(name: String, value: ClazzRef)(implicit nodeId: NodeId): ValidatedNel[PartSubGraphCompilationError, ValidationContext] =
    if (variables.contains(name)) Invalid(NonEmptyList.of(OverwrittenVariable(name))) else Valid(copy(variables = variables + (name -> value)))

  def getTypeInfo(clazzRef: ClazzRef): PlainClazzDefinition = {
    typesInformation.find(_.clazzName == clazzRef).getOrElse(throw new RuntimeException(s"Unknown clazz ref: $clazzRef"))
  }

  def pushNewContext() : ValidationContext
    = ValidationContext(Map(), typesInformation, Some(this))

  def popContext(implicit nodeId: NodeId) : ValidatedNel[PartSubGraphCompilationError, ValidationContext] = parent match {
    case Some(ctx) => Valid(ctx)
    case None => Invalid(NonEmptyList.of(NoParentContext(nodeId.id)))
  }

} 
开发者ID:TouK,项目名称:nussknacker,代码行数:36,代码来源:ValidationContext.scala

示例10: TraverseEx

//设置package包名称以及导入依赖的类
package com.memoizr.cats.traverse

import org.scalatest.{FlatSpecLike, Matchers}

class TraverseEx extends FlatSpecLike with Matchers {

  import cats.data.Xor
  import scala.concurrent.Future

  import cats.Semigroup
  import cats.syntax.traverse._
  import cats.syntax.all._
  import cats.implicits._
  import cats.Traverse.ops._
  import cats.data.{NonEmptyList, OneAnd, Validated, ValidatedNel, Xor}

  def parseIntXor(s: String): Xor[NumberFormatException, Int] = Xor.catchOnly[NumberFormatException](s.toInt)

  def parseIntValidated(s: String): ValidatedNel[NumberFormatException, Int] = Validated.catchOnly[NumberFormatException](s.toInt).toValidatedNel

  "traverse" should "traverse structure and accumulate failures" in {
    List("1", "2", "3").traverseU(parseIntXor) shouldBe Xor.Right(List(1, 2, 3))
    List("1", "abc", "3").traverseU(parseIntXor).isLeft shouldBe  true
  }

  it should "traverse and do the validation stuff" in {
    List("1", "2", "3").traverseU(parseIntValidated).isValid shouldBe true
  }

  it should "be traversable with the identity function" in {
    List(Option(1), Option(2), Option(3)).traverse(identity) shouldBe Some(List(1, 2, 3))
    List(Option(1), None, Option(3)).traverse(identity) shouldBe None
  }

  "sequence_" should "ignore the result of each computation" in {
    List(Option(1), Option(2), Option(3)).sequence_ shouldBe Some()
    List(Option(1), None, Option(3)).sequence_ shouldBe None
  }
} 
开发者ID:memoizr,项目名称:typelevel-fun,代码行数:40,代码来源:TraverseEx.scala

示例11: FeedFilters

//设置package包名称以及导入依赖的类
package com.eddsteel.feedfilter

import model._
import model.config._
import model.Errors.{ConfigLoadError, ConfigParseError}
import cats.data.{NonEmptyList, ValidatedNel}
import cats.data.Validated.{Invalid, Valid}
import cats.implicits._

import scala.io.Source

object FeedFilters {
  type ConfigErrors = NonEmptyList[ConfigParseError]

  def allFeeds: Either[ConfigErrors, List[FeedFilter[String]]] = {
    def accumulate[L, R](in: List[ValidatedNel[L, R]]): Either[NonEmptyList[L], List[R]] = {
      val (lefts, rights) = in.foldRight((List.empty[L], List.empty[R])) {
        case (Invalid(es), (ls, rs)) => (es.toList ++ ls, rs)
        case (Valid(r), (ls, rs)) => (ls, r :: rs)
      }

      lefts match {
        case (l :: ls) =>
          Left[NonEmptyList[L], List[R]](NonEmptyList(l, ls))
        case _ =>
          Right[NonEmptyList[L], List[R]](rights)
      }
    }

    def wrap[R](either: Either[ConfigParseError, R]): Either[ConfigErrors, R] =
      either.leftMap(NonEmptyList(_, Nil))

    val sourceE: Either[ConfigErrors, String] =
      wrap(
        Either
          .catchOnly[RuntimeException](Source.fromResource("feeds.yaml"))
          .map(_.mkString)
          .leftMap[ConfigParseError](e => ConfigLoadError(e)))

    for {
      source <- sourceE
      config <- wrap(YamlFeedConfig.parse(source.mkString))
      validatedConfig <- accumulate(config.map(_.toFeedConfig))
      filters = validatedConfig.map(_.toFeedFilter)
    } yield filters
  }
} 
开发者ID:eddsteel,项目名称:feed-filter,代码行数:48,代码来源:FeedFilters.scala

示例12: FeedItem

//设置package包名称以及导入依赖的类
package com.eddsteel.feedfilter.model

import Errors._
import cats.implicits._
import cats.data.{Validated, ValidatedNel}
import java.net.URI
import scala.util.Try

final case class FeedItem(id: String, title: String, href: URI, description: String)

object FeedItem {
  import scala.xml._

  type Parsed = Either[FeedItemParseError, FeedItem]

  private def handleSax[A](unsafeCall: => A): Validated[FeedItemParseError, A] =
    Validated.fromTry(Try(unsafeCall)).leftMap(SaxProblem.apply)

  def handleAttr[A](unsafeCall: => A)(key: String): ValidatedNel[XmlMarshalProblem, A] =
    Validated
      .fromTry(Try(unsafeCall))
      .leftMap(_ => AttributeMarshalProblem(key, None))
      .toValidatedNel[XmlMarshalProblem, A]

  @SuppressWarnings(Array("org.wartremover.warts.Any", "org.wartremover.warts.Nothing"))
  def fromXML(s: String): Parsed = {
    val xml = handleSax(XML.loadString(s"<root>$s</root>")).toEither
    xml.flatMap { doc =>
      val validated = (handleAttr[String]((doc \ "guid").text)("guid") |@|
        handleAttr[String]((doc \ "title").text)("title") |@|
        handleAttr[String]((doc \ "link").text)("link").map(new URI(_)) |@|
        handleAttr[String]((doc \ "description").text)("description")).map(FeedItem.apply _)

      val end: Parsed = validated.leftMap(FeedItemMarshalError.apply).toEither
      end
    }
  }
} 
开发者ID:eddsteel,项目名称:feed-filter,代码行数:39,代码来源:FeedItem.scala

示例13: YamlFeedConfig

//设置package包名称以及导入依赖的类
package com.eddsteel.feedfilter.model.config

import com.eddsteel.feedfilter.model.Errors._
import cats.data.{Validated, ValidatedNel}
import cats.implicits._
import net.jcazevedo.moultingyaml._

import java.net.URI

final case class YamlFeedConfig(name: String, src: URI, extract: String, rule: Map[String, String]) {

  @SuppressWarnings(
    Array(
      "org.wartremover.warts.Any",
      "org.wartremover.warts.Nothing"
    ))
  def toFeedConfig: ValidatedNel[ConfigParseError, FeedConfig] = {
    val validatedRule: Validated[ConfigParseError, RuleConfig] = (for {
      ruleType <- rule.get("type").toRight(MissingFeedFilterRuleField("type"))
      ruleConfig <- RuleConfig.fromFields(ruleType, rule).toRight(UnknownFeedFilterRule(rule))
    } yield ruleConfig).toValidated

    (name.validNel[ConfigParseError]
      |@| src.validNel[ConfigParseError]
      |@| ExtractorChoice.fromString(extract).toValidNel(UnknownFeedItemExtractor(extract))
      |@| validatedRule.toValidatedNel).map(FeedConfig.apply _)
  }
}

object YamlFeedConfig extends DefaultYamlProtocol {
  implicit object UriYamlFormat extends YamlFormat[URI] {
    def write(u: URI) = YamlString(u.toString)
    def read(value: YamlValue) = value match {
      case YamlString(s) =>
        try { new URI(s) } catch {
          case _: Throwable => deserializationError(s"Expected valid URI, but got $s")
        }
      case y =>
        deserializationError(s"Expected Int as YamlNumber, but got $y")
    }
  }

  implicit val format: YamlFormat[YamlFeedConfig] = yamlFormat4(YamlFeedConfig.apply)

  def parse(yaml: String): Either[ConfigParseError, List[YamlFeedConfig]] =
    Either
      .catchOnly[DeserializationException](yaml.parseYaml.convertTo[List[YamlFeedConfig]])
      .left
      .map(t => YamlParseError(t))
} 
开发者ID:eddsteel,项目名称:feed-filter,代码行数:51,代码来源:YamlFeedConfig.scala

示例14: Predicate

//设置package包名称以及导入依赖的类
package rtb
package validation

import cats.data.{NonEmptyList,Validated,ValidatedNel}
import cats.std.list._
import cats.syntax.validated._
import cats.syntax.semigroup._

final case class Predicate[A](messages: NonEmptyList[String], check: A => Boolean) {
  def apply(a: A): ValidatedNel[String,A] =
    if(check(a))
      a.validNel
    else
      Validated.invalid(messages)

  def and(that: Predicate[A]): Predicate[A] =
    Predicate(this.messages |+| that.messages, (a: A) => this.check(a) && that.check(a))
}
object Predicate {
  def lift[A](message: String)(f: A => Boolean): Predicate[A] =
    Predicate(NonEmptyList(message), f)

  def lengthAtLeast(length: Int): Predicate[String] =
    Predicate.lift(s"Must be at least $length characters."){ string =>
      string.length >= length
    }

  val onlyLettersOrDigits: Predicate[String] =
    Predicate.lift("Must contain only letters or digits."){ string =>
      string.forall(_.isLetterOrDigit)
    }

  def containsAllChars(chars: String): Predicate[String] =
    Predicate.lift(s"Must contain all of $chars"){ string =>
      val chs = chars.toList
      chs.foldLeft(true){ (accum, elt) =>
        accum && string.contains(elt)
      }
    }
} 
开发者ID:underscoreio,项目名称:rtb,代码行数:41,代码来源:predicate.scala

示例15: required

//设置package包名称以及导入依赖的类
package allawala.chassis.core.validation

import cats.data.Validated.{Invalid, Valid}
import cats.data.{NonEmptyList, ValidatedNel}

trait ValidateRequired {
  protected def required[T](name: String, value: Option[T]): ValidatedNel[ValidationError, T] = value match {
    case Some(v) => Valid(v)
    case None => Invalid(NonEmptyList.of(RequiredField(name)))
  }

  protected def requiredString(name: String, value: Option[String]): ValidatedNel[ValidationError, String] =
    required[String](name, value)
}

trait ValidateUnexpected {
  protected def unexpected[T](name: String, value: Option[T]): ValidatedNel[ValidationError, Option[T]] = value match {
    case Some(v) => Invalid(NonEmptyList.of(UnexpectedField(name)))
    case None => Valid(value)
  }

  protected def unexpectedString(name: String, value: Option[String]): ValidatedNel[ValidationError, Option[String]] =
    unexpected[String](name, value)
}

trait ValidateNotBlank {
  protected def notBlank(name: String, value: String): ValidatedNel[ValidationError, String] =
    if (value.trim.isEmpty) Invalid(NonEmptyList.of(NotBlank(name))) else Valid(value)

  protected def notBlank(name: String, value: Option[String]): ValidatedNel[ValidationError, Option[String]] = value match {
    case Some(v) => notBlank(name, v).map(_ => value)
    case None => Invalid(NonEmptyList.of(NotBlank(name)))
  }
}

trait ValidateMinLength {
  protected def minLength(name: String, value: String, min: Int): ValidatedNel[ValidationError, String] =
    if (value.trim.length < min) Invalid(NonEmptyList.of(MinLength(name, min))) else Valid(value)

  protected def minLength(name: String, value: Option[String], min: Int): ValidatedNel[ValidationError, Option[String]] = value match {
    case Some(v) => minLength(name, v, min).map(_ => value)
    case None => Invalid(NonEmptyList.of(MinLength(name, min)))
  }
}

trait ValidateMaxLength {
  protected def maxLength(name: String, value: String, max: Int): ValidatedNel[ValidationError, String] =
    if (value.trim.length > max) Invalid(NonEmptyList.of(MaxLength(name, max))) else Valid(value)

  protected def maxLength(name: String, value: Option[String], max: Int): ValidatedNel[ValidationError, Option[String]] = value match {
    case Some(v) => maxLength(name, v, max).map(_ => value)
    case None => Invalid(NonEmptyList.of(MaxLength(name, max)))
  }
}

trait Validate
  extends ValidateRequired
    with ValidateUnexpected
    with ValidateNotBlank
    with ValidateMinLength
    with ValidateMaxLength 
开发者ID:allawala,项目名称:service-chassis,代码行数:62,代码来源:Validated.scala


注:本文中的cats.data.ValidatedNel类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。