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

main.de.jensklingenberg.ktorfit.reqBuilderExtension.UrlCodeGeneration.kt Maven / Gradle / Ivy

There is a newer version: 2.2.0-1.0.28
Show newest version
package de.jensklingenberg.ktorfit.reqBuilderExtension

import de.jensklingenberg.ktorfit.model.ParameterData
import de.jensklingenberg.ktorfit.model.annotations.HttpMethodAnnotation
import de.jensklingenberg.ktorfit.model.annotations.ParameterAnnotation.Path
import de.jensklingenberg.ktorfit.model.annotations.ParameterAnnotation.Url
import de.jensklingenberg.ktorfit.model.ktorfitClass

fun getUrlCode(
    params: List,
    methodAnnotation: HttpMethodAnnotation,
    queryCode: String,
): String {
    var urlPath =
        methodAnnotation.path.ifEmpty {
            params
                .firstOrNull { it.hasAnnotation() }
                ?.let {
                    "\${${it.name}}"
                }.orEmpty()
        }

    val baseUrl =
        if (methodAnnotation.path.startsWith("http")) {
            ""
        } else {
            params.firstOrNull { it.hasAnnotation() }?.let { parameterData ->
                "(${ktorfitClass.objectName}.baseUrl.takeIf{ !${parameterData.name}.startsWith(\"http\")} ?: \"\") + "
            } ?: "${ktorfitClass.objectName}.baseUrl + "
        }

    params.filter { it.hasAnnotation() }.forEach { parameterData ->
        val paramName = parameterData.name
        val pathAnnotation = parameterData.findAnnotationOrNull()!!

        val pathEncoded =
            if (!pathAnnotation.encoded) {
                ".encodeURLPath()"
            } else {
                ""
            }
        urlPath = urlPath.replace("{${pathAnnotation.value}}", "\${\"\$${paramName}\"$pathEncoded}")
    }

    return "url{\ntakeFrom(${baseUrl}\"$urlPath\")\n" + queryCode + "}"
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy