Created
November 25, 2023 22:07
-
-
Save BFergerson/2e546158346e4c265f0613167956e0a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.assemblyai.api.resources.files | |
import com.assemblyai.api.core.ApiError | |
import com.assemblyai.api.core.ClientOptions | |
import com.assemblyai.api.core.ObjectMappers | |
import com.assemblyai.api.types.UploadedFile | |
import io.vertx.core.buffer.Buffer | |
import io.vertx.ext.web.client.HttpRequest | |
import io.vertx.ext.web.client.HttpResponse | |
import io.vertx.ext.web.client.WebClient | |
import io.vertx.kotlin.coroutines.awaitResult | |
class FilesClient(private val clientOptions: ClientOptions) { | |
private val webClient: WebClient = WebClient.create(clientOptions.vertx) | |
suspend fun upload(request: ByteArray): UploadedFile { | |
return upload(request, null) | |
} | |
suspend fun upload(request: ByteArray, requestOptions: RequestOptions?): UploadedFile { | |
val url = "${clientOptions.environment().getUrl()}/v2/upload" | |
val httpRequest: HttpRequest<Buffer> = webClient.postAbs(url) | |
.putHeader("Content-Type", "application/octet-stream") | |
.apply { | |
clientOptions.headers(requestOptions).forEach { (k, v) -> putHeader(k, v) } | |
} | |
try { | |
val response: HttpResponse<Buffer> = awaitResult { | |
httpRequest.sendBuffer(Buffer.buffer(request), it) | |
} | |
if (response.statusCode() == 200) { | |
return ObjectMappers.JSON_MAPPER.readValue(response.bodyAsString(), UploadedFile::class.java) | |
} | |
throw ApiError( | |
response.statusCode(), | |
ObjectMappers.JSON_MAPPER.readValue(response.bodyAsString(), Any::class.java) | |
) | |
} catch (e: Exception) { | |
throw RuntimeException(e) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment