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

commonMain.request.RequestBuilder.kt Maven / Gradle / Ivy

package dev.kord.rest.request

import dev.kord.common.entity.Snowflake
import dev.kord.rest.NamedFile
import dev.kord.rest.route.Route
import io.ktor.client.request.forms.*
import io.ktor.http.*
import kotlinx.serialization.SerializationStrategy

public class RequestBuilder(public val route: Route, keySize: Int = 2) {

    public var baseUrl: String = Route.baseUrl
    public val keys: MutableMap = HashMap(keySize, 1f)

    public operator fun MutableMap.set(key: Route.Key, value: Snowflake) {
        set(key, value.toString())
    }

    private val headers = HeadersBuilder()
    private val parameters = ParametersBuilder()

    private var body: RequestBody<*>? = null
    private val files: MutableList = mutableListOf()

    public operator fun MutableMap.set(key: Route.Key, value: String) {
        set(key.identifier, value)
    }

    public fun  body(strategy: SerializationStrategy, body: E) {
        this.body = RequestBody(strategy, body)
    }

    public fun parameter(key: String, value: Snowflake) {
        parameters.append(key, value.value.toString())
    }

    public fun parameter(key: String, value: Any) {
        parameters.append(key, value.toString())
    }

    /** Adds a header and encodes its [value] as an [URL query component][encodeURLQueryComponent]. */
    public fun urlEncodedHeader(key: String, value: String) {
        headers.append(key, value.encodeURLQueryComponent())
    }

    /** Adds a header without encoding its [value]. */
    public fun unencodedHeader(key: String, value: String) {
        headers.append(key, value)
    }

    public fun file(name: String, contentProvider: ChannelProvider) {
        files.add(NamedFile(name, contentProvider))
    }

    public fun file(file: NamedFile) {
        files.add(file)
    }

    public fun build(): Request<*, T> = when {
        files.isEmpty() -> JsonRequest(route, keys, parameters.build(), headers.build(), body, baseUrl)
        else -> MultipartRequest(route, keys, parameters.build(), headers.build(), body, files, baseUrl)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy