mardi 21 avril 2015

Scala: Either, Right, Left

I am new to Scala and currently trying to work with the play framework.

This is working code I wrote:

def authenticate = Action (BodyParsers.parse.json) { req =>
    req.body.validate[AuthenticationForm].map {form =>
        UserRepository.findByCredentials(form).map { user =>
            user.apiKeys.find(_.deviceId == form.deviceId).map { apiKey =>
                Ok(Json.toJson(apiKey))
            }.getOrElse({
                // HOW DO I TRANSFORM THIS INTO MORE BEAUTIFUL CODE
                val createdApiKey = ApiKeyRepository.create(new ApiKey(form.deviceId, form.deviceId))
                val userToWithNewApiKey = user.copy(apiKeys = user.apiKeys.:+(createdApiKey))
                UserRepository.update(userToWithNewApiKey)

                Ok(Json.toJson(createdApiKey))
            })
        }.getOrElse {
            Unauthorized
        }
    }.getOrElse {
        BadRequest
    }
}

Well, that does not look tooo nice. Can we do better? I can not, yet. But I saw this stackoverflow post: http://ift.tt/1yOAFOg That looks pretty nice :)

Now I am wondering, how to transform my code, so it looks like in the given example. Of course I already tried, but I could not make it compile and also do not know how to handle the code after the comment ("HOW DO I TRANSFORM THIS INTO MORE BEAUTIFUL CODE"). In my case I am using play.api.mvc.Result instead of "Failure" as given in the link above. So of what type should my Either[play.api.mvc.Result, ?WhatHere?] be?

Best regards

Aucun commentaire:

Enregistrer un commentaire