我想验证我的API的完整函数的结果,当它无法将String转换为Json类型时,Response生成null,我不希望它生成null但是说:“not found”,这是我的路线:
val route = pathPrefix("auth") {
path("signIn") {
pathEndOrSingleSlash {
post {
entity(as[LoginPassword]) { loginPassword =>
val a = signIn(loginPassword.login, loginPassword.password).map(_.asJson)
if(signIn(loginPassword.login, loginPassword.password).map(_.asJson) == null){
complete(states.map(_.asJson))
}else {
def getObject : Option[Any] = Option(signIn(loginPassword.login, loginPassword.password).map(_.asJson))
val ahh = signIn(loginPassword.login, loginPassword.password).map(_.asJson)
if(getObject.isEmpty || getObject == null){ ///////NOT FOUND
complete("Not Found")
}else {
complete(signIn(loginPassword.login, loginPassword.password).map(_.asJson)
}
//complete(signIn(loginPassword.login, loginPassword.password).map(_.asJson))
}
}
}
}
}
这不起作用,因为它总是在条件中进入else,当它在BD中获取值时响应Json而在不是时返回null。
功能标志
def signIn(login: String, password: String): Future[Option[TokenEntity]] = {
db.run(users.filter(u => u.username === login).result).flatMap { users =>
users.find(user => Bcrypt.validate(password, user.password)) match {
case Some(user) => db.run(tokens.filter(_.userId === user.id).result.headOption).flatMap {
case Some(token) => Future.successful(Some(token))
case None => createToken(user).map(token => Some(token))
}
case None => Future.successful(None)
}
}
}
我使用的Json库是:Json
有些帮助吗?感谢。
答案 0 :(得分:0)
我停下来思考问题以及如何解决我需要的问题并首先验证这是一个有效的响应是分析signIn的响应:
将响应分配给val
val token = signIn(loginPassword.login, loginPassword.password)
令牌的类型为:Future [Option [TokenEntity]],我需要使用:Option [TokenEntity]并验证它是否是正确答案:
val response = token.map(_ match {
case Some(token) => prepareHttpResponse(StatusCodes.OK, token.asJson.toString)
case None => prepareHttpResponse(StatusCodes.Unauthorized, "{reason: \"not found\"")
})
如果它有效我以Json格式回复令牌,但我回复:未找到 终于是:
val route = pathPrefix("auth") {
path("signIn") {
post {
entity(as[LoginPassword]) { loginPassword =>
val token = signIn(loginPassword.login, loginPassword.password)
val response = token.map(_ match {
case Some(token) => prepareHttpResponse(StatusCodes.OK, token.asJson.toString)
case None => prepareHttpResponse(StatusCodes.Unauthorized, "{reason: \"not found\"")
})
complete(response)
}
}
}