Created
December 13, 2019 07:57
-
-
Save softberries/da9c3eb592de13725f1c1ed2c3eaf67e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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