Search code examples
mongodbscalaakka-httpcase-classspray-json

Same case class different validation


What I'm trying to do in Scala 2.11 and akka is have one case class but two different validations based on which route is being hit.

For example, let's consider the case class below

case class User(_id: String, name: String, age: Int, address: String)

Now while the /create route is hit, I don't need _id but I need all the other fields.

But while /update route is hit, I need the _id and the fields that are to be updated (which could be one or all three)

Only declaring Option doesn't serve the purpose because then my /create route goes for a toss.

Even extending case classes doesn't really work seamlessly (there's too much code duplicity).

I would love if something like this was possible

case class User(_id: String, name: String, age: Int, address: String)

case class SaveUser() extends User {
    require(name.nonEmpty)
    require(age.nonEmpty)
    require(address.nonEmpty)
}

case class UpdateUser() extends User {
    require(_id.nonEmpty)
}

Is there an elegant solution to this? Or do I have to create two identical case classes?


Solution

  • My suggestion would be to encode different case classes for different requirements, but if you insist you must share code between these two cases a possible solution would be to parameterize the case class

    case class User[Id[_], Param[_]](_id: Id[String], name: Param[String], age: Param[Int], address: Param[String])
    

    Then you define an alias for the Identity type constructor and your two uses of the case class

    type Identity[T] = T
    type SaveUser = User[Option, Identity]
    type UpdateUser = User[Identity, Option]