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

commonMain.com.algolia.client.extensions.internal.SearchClient.kt Maven / Gradle / Ivy

Go to download

"Algolia is a powerful search-as-a-service solution, made easy to use with API clients, UI libraries, and pre-built integrations. Algolia API Client for Kotlin lets you easily use the Algolia Search REST API from your JVM project, such as Android or backend implementations."

There is a newer version: 3.10.1
Show newest version
package com.algolia.client.extensions.internal

import com.algolia.client.api.SearchClient
import com.algolia.client.model.search.SearchParamsObject
import com.algolia.client.model.search.SecuredApiKeyRestrictions
import io.ktor.http.*
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.collections.LinkedHashMap

/**
 * Builds a restriction string based on provided [SecuredApiKeyRestrictions].
 */
internal fun SearchClient.buildRestrictionString(restriction: SecuredApiKeyRestrictions): String {
  val sortedParams = LinkedHashMap()

  restriction.searchParams?.let { searchParams ->
    val json = options.json.encodeToJsonElement(SearchParamsObject.serializer(), searchParams).jsonObject
    json.forEach { (key, element) ->
      val value = when (element) {
        is JsonArray -> element.joinToString(",") { it.jsonPrimitive.content }
        else -> element.jsonPrimitive.content
      }
      sortedParams.put(key, value)
    }
  }

  restriction.restrictIndices?.let {
    sortedParams["restrictIndices"] = it.joinToString(",")
  }
  restriction.restrictSources?.let {
    sortedParams["restrictSources"] = it
  }
  restriction.userToken?.let {
    sortedParams["userToken"] = it
  }
  restriction.filters?.let {
    sortedParams["filters"] = it
  }
  restriction.validUntil?.let {
    sortedParams["validUntil"] = it.toString()
  }

  return sortedParams.entries
    .sortedBy { it.key }
    .joinToString("&") { "${it.key}=${it.value.encodeURLParameter()}" }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy