All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.elderscrollslegends.QueryBuilder.kt Maven / Gradle / Ivy

There is a newer version: 1.1.7
Show newest version
package io.elderscrollslegends

class QueryBuilder : Config() {
    private val unirestClient = UnirestClient(uriPath = "${config[legendsAPIUri]}/${config[legendsAPIVersion]}")

    fun  find(resource: String, id: String, cls: Class, queryParams: Map = emptyMap()): T? {
        return unirestClient.find(resource, id, cls, queryParams)
    }

    fun  where(resource: String, cls: Class, predicates: Map = emptyMap(), adder: (S?, MutableList) -> Unit): List {
        val adjustedPredicates = predicates.toMutableMap()

        val singlePageOnly = predicates.containsKey("page")

        val page = adjustedPredicates.getOrDefault("page", "1")
        adjustedPredicates["page"] = page

        val items = unirestClient.get(resource = resource, cls = cls, queryParams = adjustedPredicates) ?: return emptyList()

        val results = mutableListOf()
        adder(items, results)

        if (singlePageOnly) return results

        val totalPageCount = items.totalCount / items.pageSize + if (items.totalCount % items.pageSize == 0) 0 else 1
        for (nextPage in (page.toInt() + 1)..totalPageCount) {
            adjustedPredicates["page"] = nextPage.toString()
            val newItems = unirestClient.get(resource = resource, cls = cls, queryParams = adjustedPredicates)
            adder(newItems, results)
        }

        return results
    }
}