From 4be50e4fa7450c95d3049fb4503ecdfeaef8eff6 Mon Sep 17 00:00:00 2001 From: Alexis Hernandez Date: Wed, 14 Mar 2018 12:22:15 -0600 Subject: [PATCH] server: Add Address model --- .../app/com/xsn/explorer/models/Address.scala | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 server/app/com/xsn/explorer/models/Address.scala diff --git a/server/app/com/xsn/explorer/models/Address.scala b/server/app/com/xsn/explorer/models/Address.scala new file mode 100644 index 0000000..8cac14a --- /dev/null +++ b/server/app/com/xsn/explorer/models/Address.scala @@ -0,0 +1,32 @@ +package com.xsn.explorer.models + +import play.api.libs.json._ + +class Address private (val string: String) extends AnyVal + +object Address { + + private val pattern = "^[a-zA-Z0-9]{34}$".r.pattern + + def from(string: String): Option[Address] = { + if (pattern.matcher(string).matches()) { + Some(new Address(string)) + } else { + None + } + } + + implicit val reads: Reads[Address] = Reads { json => + json.validate[String].flatMap { string => + from(string) + .map(JsSuccess.apply(_)) + .getOrElse { + JsError.apply("Invalid address") + } + } + } + + implicit val writes: Writes[Address] = Writes { obj => + JsString(obj.string) + } +}