How to assert length two array or value for field?

27 views
Skip to first unread message

John Ky

unread,
Jun 15, 2014, 8:36:56 PM6/15/14
to argona...@googlegroups.com
Hi Everyone,

Is there a way to assert that the length of an array is two when decoding?

Or that a field in a Json object has a particular value?

Cheers,

-John



  Sydney, Australia

        

John Ky

unread,
Jun 16, 2014, 12:14:46 AM6/16/14
to argona...@googlegroups.com
Hello,

Thanks to Mark earlier on the tip with the validate method.

I'd like to ask a stylistic question.  I have a decoder that decodes [1, "s"] into 1 second, [2, "ns"] into 2 nanosecond, and fails to decode if the array is the wrong length or if the unit string is not recognised.  I currently interpret the unit string with a pattern match on DecodeResult.  Is this the most stylistically optimal way to express this behaviour in a decoder?  Code below.

Cheers,

-John

import argonaut._
import argonaut.Argonaut._
import scala.concurrent.duration._
import scalaz.{-\/, \/, \/-}

trait DurationDecoder {
  implicit def argoDecodeDuration: DecodeJson[FiniteDuration] = {
    DecodeJson { c =>
      for {
        number <- (c =\ 0).as[Long]
        duration <- {
          val cc = (c =\ 1)

          (cc.as[String] match {
            case DecodeResult(\/-(unit)) =>
              unit match {
                case "d"  => DecodeResult.ok(number days)
                case "h"  => DecodeResult.ok(number hours)
                case "m"  => DecodeResult.ok(number minutes)
                case "s"  => DecodeResult.ok(number seconds)
                case "ms" => DecodeResult.ok(number milliseconds)
                case "us" => DecodeResult.ok(number microseconds)
                case "ns" => DecodeResult.ok(number nanoseconds)
                case _    => DecodeResult.fail(s"Invalid duration unit '$unit'", cc.history)
              }
            case failure => DecodeResult.fail(s"Expected duration unit", cc.history)
          })
        }
      } yield duration
    }.validate({ c => (c =\ 2).failed }, "Too many elements for duration")
  }
}

object DurationCodec extends DurationCodec

Reply all
Reply to author
Forward
0 new messages