icerockdev / moko-network

Network components with codegeneration of rest api for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev
Apache License 2.0
151 stars 29 forks source link

FormData with files support #122

Closed Alex009 closed 1 year ago

Alex009 commented 3 years ago

Now generated:

override suspend fun signup(signup: SignupRequest?, avatar: kotlin.String?) : Response {
        val builder = HttpRequestBuilder()

        builder.method = HttpMethod.Post
        builder.url {
            takeFrom(_basePath)
            encodedPath = encodedPath.let { startingPath ->
                path("v1/auth/signup")
                return@let startingPath + encodedPath.substring(1)
            }
        }

        val formData = FormDataContent(Parameters.build {
            signup?.let { append("signup", it.toString()) }
            avatar?.let { append("avatar", it.toString()) }
        })
        builder.body = formData
        with(builder.headers) {
            append("Accept", "application/json")
        }

        try {
                val serializer = Response.serializer()

                //not primitive type
                val result: String = _httpClient.request(builder)
                return _json.decodeFromString(serializer, result)
        } catch (pipeline: ReceivePipelineException) {
            throw pipeline.cause
        }
    }

but should be:

suspend fun signUp(imageFile: Bitmap?, userInfo: SignupRequest) {
        try {
            val byteArray: ByteArray =
                imageFile?.getResizedBitmap(maxSize = 1024)?.toByteArray() ?: ByteArray(0)

            val fileName = "avatar.jpg"

            httpClient.submitFormWithBinaryData<String> {
                url {
                    takeFrom(basePath)
                    encodedPath = encodedPath.let { startingPath ->
                        path("/v1/auth/signup")
                        return@let startingPath + encodedPath.substring(1)
                    }
                }
                body = MultiPartFormDataContent(
                    formData {
                        append(
                            key = "signup",
                            value = json.encodeToString(
                                SignupRequest.serializer(),
                                userInfo
                            )
                        )
                        append(
                            key = "avatar",
                            value = byteArray,
                            headers = Headers.build {
                                append(HttpHeaders.ContentDisposition, "filename=${fileName}")
                            }
                        )
                    }
                )
            }
        } catch (pipeline: ReceivePipelineException) {
            throw pipeline.cause
        }
    }
Alex009 commented 1 year ago

will be released in 0.21.0