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

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

Go to download

A java wrapper around the Elder Scrolls: Legends API of https://elderscrollslegends.io

The newest version!
package io.elderscrollslegends

class QueryBuilder {
    private val unirestClient = UnirestClient()

    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
    }
}