Files
LMS-APIs/src/main/kotlin/routes/PatronRoutes.kt

92 lines
3.9 KiB
Kotlin

package codes.kalar.routes
import codes.kalar.exception.DbElementInsertionException
import codes.kalar.exception.DbElementNotFoundException
import codes.kalar.model.NewPatron
import codes.kalar.model.Patron
import codes.kalar.service.PatronService
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.authenticate
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.sql.Connection
fun Application.configurePatronRoutes(dbConnection: Connection) {
val patronService = PatronService(dbConnection)
routing {
get("/patron/{id}") {
try {
val id = call.pathParameters["id"]!!.toLong()
val patron = patronService.readPatronById(id)
call.respond(HttpStatusCode.OK, patron)
} catch (cause: DbElementInsertionException) {
call.respond(HttpStatusCode.BadRequest, cause.message ?: "Unknown error")
} catch (cause: NumberFormatException) {
call.respond(HttpStatusCode.BadRequest, cause.message ?: "Unknown error")
}
}
get("/patron") {
try {
val username = call.parameters["username"]
if (username == null) {
call.respond(HttpStatusCode.BadRequest, "username & password required")
} else {
val patron = patronService.readPatronByLoginUsername(username)
call.respond(HttpStatusCode.OK, patron)
}
} catch (cause: DbElementNotFoundException) {
call.respond(HttpStatusCode.BadRequest, "Username not found")
}
}
authenticate("staff") {
post("/patron") {
try {
val patron = call.receive<NewPatron>()
val id = patronService.create(patron)
call.respondText("Adding ${patron.name} to database with the id of $id", status = HttpStatusCode.OK)
} catch (cause: DbElementInsertionException) {
call.respond(HttpStatusCode.BadRequest, cause.message ?: "Bad Arguments")
} catch (cause: ContentTransformationException) {
call.respond(HttpStatusCode.BadRequest, "Bad Arguments. Must pass a valid CollectionItem object.")
}
}
}
authenticate("general") {
patch("/patron") {
try {
val patron = call.receive<Patron>()
val isPatched = patronService.update(patron)
if (isPatched) {
call.respond(HttpStatusCode.OK, "${patron.name} is patched")
} else {
call.respond(HttpStatusCode.BadRequest, "${patron.name} is not patched")
}
} catch (cause: DbElementInsertionException) {
call.respond(HttpStatusCode.BadRequest, cause.message ?: "Unable to update Patron.")
} catch (cause: ContentTransformationException) {
call.respond(HttpStatusCode.BadRequest, "Bad Arguments. Must pass a valid Patron object.")
}
}
}
authenticate("staff") {
delete("/patron/{id}") {
try {
val id = call.pathParameters["id"]!!.toLong()
patronService.delete(id)
call.respond(HttpStatusCode.OK, "Successfully deleted the patron")
} catch (cause: DbElementInsertionException) {
call.respond(HttpStatusCode.BadRequest, cause.message ?: "Unable to delete Patron.")
} catch (cause: NumberFormatException) {
call.respond(HttpStatusCode.BadRequest, cause.message ?: "ID needs to be a number.")
}
}
}
}
}