優化sendUnauthorized、sendNotFound

This commit is contained in:
Raymond Yang 2023-05-16 10:36:54 +08:00
parent 50dbcf60e1
commit 07597ad5f2
2 changed files with 8 additions and 8 deletions

View File

@ -20,10 +20,10 @@ suspend fun <T : Any> ApplicationCall.sendSuccess(data: T?) {
) )
} }
suspend fun ApplicationCall.sendUnauthorized(errorResponse: ErrorResponse) { suspend fun ApplicationCall.sendUnauthorized() {
this.respond( this.respond(
status = HttpStatusCode.Unauthorized, status = HttpStatusCode.Unauthorized,
message = errorResponse message = ErrorResponse.UNAUTHORIZED_RESPONSE
) )
} }
@ -34,9 +34,9 @@ suspend fun ApplicationCall.sendBadRequest(errorResponse: ErrorResponse) {
) )
} }
suspend fun ApplicationCall.sendNotFound(errorResponse: ErrorResponse) { suspend fun ApplicationCall.sendNotFound() {
this.respond( this.respond(
status = HttpStatusCode.NotFound, status = HttpStatusCode.NotFound,
message = errorResponse message = ErrorResponse.NOT_FOUND_RESPONSE
) )
} }

View File

@ -50,18 +50,18 @@ fun Application.configureUserRouting() {
} }
call.sendSuccess(LoginResult(request.account, token!!)) call.sendSuccess(LoginResult(request.account, token!!))
} else { } else {
call.sendUnauthorized(ErrorResponse("Account or Password wrong.")) call.sendBadRequest(ErrorResponse("Account or Password wrong."))
} }
} }
authenticate { authenticate {
post("/logout") { post("/logout") {
val account = call.authentication.principal<UserDto>()?.account ?: run { val account = call.authentication.principal<UserDto>()?.account ?: run {
call.sendUnauthorized(ErrorResponse("Unauthorized")) call.sendUnauthorized()
return@post return@post
} }
val user = service.findByAccount(account) ?: run { val user = service.findByAccount(account) ?: run {
call.sendUnauthorized(ErrorResponse("Unauthorized")) call.sendUnauthorized()
return@post return@post
} }
user.apply { user.apply {
@ -83,7 +83,7 @@ fun Application.configureUserRouting() {
val id = call.parameters["id"].toString() val id = call.parameters["id"].toString()
service.findById(id) service.findById(id)
?.let { foundPerson -> call.respond(foundPerson.toDto()) } ?.let { foundPerson -> call.respond(foundPerson.toDto()) }
?: call.sendNotFound(ErrorResponse.NOT_FOUND_RESPONSE) ?: call.sendNotFound()
} }
get("/search") { get("/search") {