2. CONTACTS AS A SERVICE
Should have JSON endpoints for
• Store contact information
• Retrieval by Name
Contacts as a Service
https://github.com/FortyTwoEng/
Contacts-As-A-Service/blob/master/
app/controllers/Application.scala
3. • OO Representation
• Handle JSON requests and convert to OO
• Save to DB/Load from DB
What do we need?
4. • OO Representation
• Handle JSON requests and convert to OO
• Save to DB/Load from DB
What do we need?
5. SCALA REPRESENTATION
case class Email(addr: String)
case class Contact(
name: String,
phone: Option[Int],
email: Option[Email]
)
6. • OO Representation
• Handle JSON requests and convert to OO
• Save to DB/Load from DB
What do we need?
9. MACROS!
object Contact {
implicit val format: Format[Contact] =
Json.format[Contact]
}
Almost, but not quite: Can’t deal with Email
case class Email(addr: String)
case class Contact(
name: String,
phone: Option[Int],
email: Option[Email]
)
MAGIC!
10. FORMAT BY HAND
object Email {
implicit format : Format[Email] = Json.format[Email]
}
Let’s not be lazy
11. FORMAT BY HAND
object Email {
implicit val format = new Format[Email]{
def reads(json: JsValue) : JsResult[Email] = {
json match{
case JsString(s) => JsSuccess(Email(s))
case _ => JsError()
}
}
def writes(email: Email) : JsValue = {
JsString(email.addr)
}
}
}
12. ACCEPTING JSON
REQUESTS
def store(name: String) = Action(parse.tolerantJson)
{ request =>
val phoneJson : JsValue = request.body "phone"
val phone : Option[Int] = phoneJson.asOpt[Int]
val email = (request.body "email").asOpt[Email]
val contact = Contact(name, phone, email)
saveToDb(contact)
Ok(“”)
}
13. ALL TOGETHER NOW
def lookup(name: String) = Action { request =>
val contacts : Seq[Contact] = loadFromDb(name)
val contactsJson : Seq[JsValue] =
contacts.map(Json.toJson(_))
Ok(JsArray(contactsJson))
}
def store(name: String) = Action(parse.tolerantJson)
{ request =>
val phoneJson : JsValue = request.body "phone"
val phone : Option[Int] = phoneJson.asOpt[Int]
val email = (request.body "email").asOpt[Email]
val contact = Contact(name, phone, email)
saveToDb(contact)
Ok(“”)
}
14. • OO Representation
• Handle JSON requests and convert to OO
• Save to DB/Load from DB
What do we need?