Skip to content

Instantly share code, notes, and snippets.

@oharaandrew314
Last active January 25, 2022 01:26
Show Gist options
  • Save oharaandrew314/939c7f1033a731781935f39865113aad to your computer and use it in GitHub Desktop.
Save oharaandrew314/939c7f1033a731781935f39865113aad to your computer and use it in GitHub Desktop.
class RestApi(private val pets: PetService) {
companion object {
val petIdLens = Path.long().of("petId")
val petLens = Body.auto<Pet>().toLens()
val nameLens = Query.nonEmptyString().required("name")
const val petsPath = "/pet"
val petPath = "/pet/${petIdLens}"
val uploadImagePath = "/pet/${petIdLens}/uploadImage"
}
private fun getPet(request: Request): Response {
val id = petIdLens(request)
val pet = pets.get(id) ?: return Response(Status.NOT_FOUND)
return Response(Status.OK).with(petLens of pet)
}
private fun createPet(request: Request): Response {
val name = nameLens(request)
val pet = pets.create(name = name)
return Response(Status.OK).with(petLens of pet)
}
private fun uploadImage(request: Request): Response {
val contentType = Header.CONTENT_TYPE(request) ?: return Response(Status.BAD_REQUEST)
val petId = petIdLens(request)
val updatedPet = request.body.use { body ->
pets.uploadImage(petId, contentType.value, body.stream)
} ?: return Response(Status.NOT_FOUND)
return Response(Status.OK).with(petLens of updatedPet)
}
fun toHttpHandler() : HttpHandler {
val routes = routes(
petPath bind Method.GET to ::getPet,
petsPath bind Method.POST to ::createPet,
uploadImagePath bind Method.POST to ::uploadImage
)
return ServerFilters.CatchLensFailure().then(routes)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment