Created
March 16, 2018 10:45
-
-
Save alwarren/a94745ebed40b8e280616b7d8d61da45 to your computer and use it in GitHub Desktop.
A helper class for creating REST endpoints.
This file contains hidden or 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
/** | |
* A helper class for building REST API endpoints. | |
*/ | |
class Endpoint( | |
val path: String, | |
val query: String, | |
val value: String) { | |
// Returns a list of objects containing a subset of object properties | |
class Filter { | |
companion object { | |
fun someThing(value: String): Endpoint = Endpoint("filter.php", "a", value) | |
fun someOtherThing(value: String): Endpoint = Endpoint("filter.php", "b", value) | |
} | |
} | |
// Returns a list of objects containing complete objects | |
class Search { | |
companion object { | |
fun someThing(value: String): Endpoint = Endpoint("search.php", "a", value) | |
fun someOtherThing(value: String): Endpoint = Endpoint("search.php", "b", value) | |
} | |
} | |
// Returns a list containing a single object | |
class Lookup { | |
companion object { | |
fun getById(value: String): Endpoint = Endpoint("lookup.php", "a", value) | |
fun getRandom(): Endpoint = Endpoint("random.php", "", "") | |
} | |
} | |
// Returns a list of strings | |
class List { | |
companion object { | |
fun someCategory(): Endpoint = Endpoint("list.php", "a", "list") | |
fun someOtherCategory(): Endpoint = Endpoint("list.php", "b", "list") | |
} | |
} | |
// There are some cases where we want to know if this is a filter | |
fun isFilter(): Boolean { | |
return path == "filter" | |
} | |
// This is used with Retrofit @QueryMap | |
fun options(): Map<String, String> { | |
if (query.isEmpty() && value.isEmpty()) | |
return emptyMap() | |
val map = HashMap<String, String>() | |
map.put(query, value) | |
return map | |
} | |
override fun toString(): String { | |
return "Endpoint(path='$path', query='$query', value='$value')" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment