Created
June 10, 2018 18:10
-
-
Save juancho088/56e1a13cc391d5233a02369717317064 to your computer and use it in GitHub Desktop.
Simple Controller without dynamic routing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.myblockbuster.core.controllers | |
import com.fasterxml.jackson.databind.ObjectMapper | |
import com.myblockbuster.core.InvalidArguments | |
import com.myblockbuster.core.Model | |
import com.myblockbuster.core.Request | |
/** | |
* Controller that receives a request and reply with a message of type {@link M} | |
* @param M Model type | |
*/ | |
interface Controller<M> { | |
fun anyToInt(value: Any, valueType: String = "page"): Int { | |
return when (value) { | |
is String -> value.toIntOrNull() ?: throw Exception("$valueType must be a number") | |
is Int -> value | |
else -> throw Exception("$valueType must be a number") | |
} | |
} | |
fun getStringAnyMap(request: Request, key: String): Map<String, Any> { | |
return if (request.input.containsKey(key) && request.input[key] != null) | |
request.input[key] as Map<String, Any> | |
else | |
emptyMap() | |
} | |
fun getResource(request: Request): String { | |
return request.input["resource"] as String | |
} | |
fun getHeaders(request: Request) : Map<String, Any> { | |
return getStringAnyMap(request, "headers") | |
} | |
fun getPathParameters(request: Request) : Map<String, Any> { | |
return getStringAnyMap(request, "pathParameters") | |
} | |
fun getQueryStringParameters(request: Request) : Map<String, Any> { | |
return getStringAnyMap(request, "queryStringParameters") | |
} | |
fun getRawBody(request: Request) : Any { | |
if (request.input["body"] != null) | |
return if (request.input["body"] is String) request.input["body"] as String else request.input["body"] as Map<String, Any> | |
else | |
throw InvalidArguments("body") | |
} | |
fun <T : Model> getEntity(rawBody: Any, cls: Class<T>): T { | |
val objectMapper = ObjectMapper() | |
return if (rawBody is String) objectMapper.readValue(rawBody, cls) else objectMapper.convertValue(rawBody, cls) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment