Skip to content

Instantly share code, notes, and snippets.

@supermanue
Last active March 22, 2022 07:37
Show Gist options
  • Save supermanue/163673ce6f52e58deaecda948276cb3f to your computer and use it in GitHub Desktop.
Save supermanue/163673ce6f52e58deaecda948276cb3f to your computer and use it in GitHub Desktop.
Using users
//creating
val maybeUser: Either[RefinedTypeError, User] = User.build(input.id, input.name)
//accesing
val id = user.id.value
val name = user.name.value
//create user in the UserService needs a for comprehension
def createUser(id: Int, name: String): ZIO[UserPersistence, AppError, User] =
for {
user <- ZIO.fromEither(User.build(id, name))
stored <- RIO.accessM[UserPersistence](_.get.create(user))
} yield stored
//API layer: return a 400 with wrong input
case request @ POST -> Root =>
request.decode[UserInput] { userInput =>
UserService
.createUser(userInput.id, userInput.name)
.foldM(
{
case error: DBError => ServiceUnavailable(error.message)
case error: RefinedTypeError => BadRequest(error.message) ///THIS IS NEW
case other => InternalServerError(other.message)
},
Created(_)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment