Skip to content

Instantly share code, notes, and snippets.

@juancho088
Created June 11, 2018 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juancho088/209bdd6d92bdaf419b5a6d6e014d503e to your computer and use it in GitHub Desktop.
Save juancho088/209bdd6d92bdaf419b5a6d6e014d503e to your computer and use it in GitHub Desktop.
// You can add this code to the Controller.kt class
companion object {
// HTTP constants
const val HTTP_METHOD: String = "httpMethod"
const val HTTP_GET: String = "get"
const val HTTP_POST: String = "post"
const val HTTP_PUT: String = "put"
const val HTTP_DELETE: String = "delete"
const val HTTP_PATCH: String = "patch"
// Pagination constants
const val LIMIT: Int = 50
const val MAX_LIMIT: Int = 100
const val OFFSET: Int = 0
const val MIN_LIMIT: Int = 0
}
fun getPagination(queryParameters: Map<String, Any>): Pagination {
var page: Int = ceil(OFFSET.toDouble() / LIMIT).toInt()
var size: Int = LIMIT
val pagination = Pagination(page, size)
if (queryParameters.containsKey("page")) {
page = anyToInt(queryParameters["page"]!!)
pagination.page = if (page >= MIN_LIMIT + 1) page - 1 else MIN_LIMIT
}
if (queryParameters.containsKey("size")) {
size = anyToInt(queryParameters["size"]!!, "size")
pagination.size = if (size < MAX_LIMIT) size else MAX_LIMIT
}
return pagination
}
/**
* Http router, it receives a class type to return, a request and service to automatically execute and return a response
* @param cls Class return type
* @param request Http Client request
* @param service CRUD service to execute
*/
fun <T : Model> defaultRouting(cls: Class<T>, request: Request, service: Service<T, User>): Any {
val resource: String = getResource(request)
val headers: Map<String, Any> = getHeaders(request)
val pathParameters: Map<String, Any> = getPathParameters(request)
val queryParameters: Map<String, Any> = getQueryStringParameters(request)
return when((request.input[HTTP_METHOD] as String).toLowerCase()) {
HTTP_GET -> {
when {
resource.endsWith("findOne", true) -> service.findOne(AnonymousUser(), queryParameters)
pathParameters.containsKey("id") -> {
val id = pathParameters["id"]
when (id) {
is Int -> service.findOne(AnonymousUser(), id)
else -> throw Exception("Id must be an integer")
}
}
else -> {
return service.findAll(AnonymousUser(), queryParameters, getPagination(queryParameters))
}
}
}
HTTP_POST -> {
service.create(AnonymousUser(), getEntity(getRawBody(request), cls))
}
HTTP_PUT -> {
service.update(AnonymousUser(), getEntity(getRawBody(request), cls))
}
HTTP_DELETE -> {
service.delete(AnonymousUser(), getEntity(getRawBody(request), cls).id!!)
}
HTTP_PATCH -> {
service.update(AnonymousUser(), getEntity(getRawBody(request), cls))
}
else -> {
throw Exception()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment