gpt4 book ai didi

scala - 可选的 Json 正文解析器

转载 作者:行者123 更新时间:2023-12-04 15:58:23 26 4
gpt4 key购买 nike

我正在尝试使用 PlayFramework 编写 DRY CRUD Restful 服务。这是它的代码。

def crudUsers(operation: String) = Action(parse.json) { request =>
(request.body).asOpt[User].map { jsonUser =>
try {
DBGlobal.db.withTransaction {
val queryResult = operation match {
case "create" =>
UsersTable.forInsert.insertAll(jsonUser)
Json.generate(Map("status" -> "Success", "message" -> "Account inserted"))

case "update" =>
val updateQ = UsersTable.where(_.email === jsonUser.email.bind).map(_.forInsert)
println(updateQ.selectStatement)
updateQ.update(jsonUser)
Json.generate(Map("status" -> "Success", "message" -> "Account updated"))

case "retrieve" =>
val retrieveQ = for(r <- UsersTable) yield r
println(retrieveQ.selectStatement)
Json.generate(retrieveQ.list)

case "delete" =>
val deleteQ = UsersTable.where(_.email === jsonUser.email)
deleteQ.delete
Json.generate(Map("status" -> "Success", "message" -> "Account deleted"))
}
Ok(queryResult)
}
} catch {
case _ =>
val errMsg: String = operation + " error"
BadRequest(Json.generate(Map("status" -> "Error", "message" -> errMsg)))
}
}.getOrElse(BadRequest(Json.generate(Map("status" -> "Error", "message" -> "error"))))

}

我注意到更新、删除和创建操作运行良好。但是,检索操作失败并显示 For request 'GET/1/users' [Invalid Json]。我很确定这是因为 JSON 解析器不能容忍没有在正文中传递 JSON 的 GET 请求。

有没有一种方法可以在不丢失我在这里开始的 DRY 方法的情况下对 GET/Retrieve 操作进行特殊处理?

最佳答案

我的猜测是您拆分了方法,以便为有和没有主体的方法创建不同的路由。

看来即使把空字符串解析成JSON,代码的设计也不行。 map 方法不会被执行,因为没有用户。这将导致永远不会执行匹配操作。

更新

既然你提到了 DRY,我会把它重构成这样:

  type Operations = PartialFunction[String, String]

val operations: Operations = {
case "retrieve" =>
println("performing retrieve")
"retrieved"
case "list" =>
println("performing list")
"listed"
}

def userOperations(user: User): Operations = {
case "create" =>
println("actual create operation")
"created"
case "delete" =>
println("actual delete operation")
"updated"
case "update" =>
println("actual update operation")
"updated"
}

def withoutUser(operation: String) = Action {
execute(operation, operations andThen successResponse)
}

def withUser(operation: String) = Action(parse.json) { request =>
request.body.asOpt[User].map { user =>
execute(operation, userOperations(user) andThen successResponse)
}
.getOrElse {
errorResponse("invalid user data")
}
}

def execute(operation: String, actualOperation: PartialFunction[String, Result]) =
if (actualOperation isDefinedAt operation) {
try {
DBGlobal.db.withTransaction {
actualOperation(operation)
}
} catch {
case _ => errorResponse(operation + " error")
}
} else {
errorResponse(operation + " not found")
}

val successResponse = createResponse(Ok, "Success", _: String)
val errorResponse = createResponse(BadRequest, "Error", _: String)

def createResponse(httpStatus: Status, status: String, message: String): Result =
httpStatus(Json.toJson(Map("status" -> status, "message" -> message)))

关于scala - 可选的 Json 正文解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10809799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com