Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package services
import cats.MonadError
import models.Person
import repositories.PersonRepository
import cats.implicits._
class PersonService[F[_]](personRepository: PersonRepository[F])(
implicit monadError: MonadError[F, String]
) {
def createPerson(person: Person): F[Person] =
for {
_ <- monadError.fromEither(validatePerson(person))
mayBeUser <- personRepository.get(person.name)
_ <- mayBeUser.fold(person.pure[F])(_ => monadError.raiseError("User with the given name already exist"))
p <- personRepository.create(person.name, person.age)
} yield p
def list(): F[Seq[Person]] = personRepository.list()
private def validatePerson(person: Person): Either[String, Person] = {
if (person.age >= 18) {
Right(person)
} else {
Left("Too young to participate")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.