From 0ceee5ed4bae240b8c8e94d2fd7424d9d0b67ec7 Mon Sep 17 00:00:00 2001 From: Jakob Odersky Date: Wed, 9 Oct 2019 17:10:43 -0400 Subject: Migrate build to mill --- ui/src/http/XhrBackend.scala | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 ui/src/http/XhrBackend.scala (limited to 'ui/src/http/XhrBackend.scala') diff --git a/ui/src/http/XhrBackend.scala b/ui/src/http/XhrBackend.scala new file mode 100644 index 0000000..3a791c1 --- /dev/null +++ b/ui/src/http/XhrBackend.scala @@ -0,0 +1,51 @@ +package triad +package http + +import org.scalajs.dom.{ErrorEvent, Event, XMLHttpRequest} + +import scala.concurrent.{Future, Promise, TimeoutException} +import scala.scalajs.js +import scala.scalajs.js.typedarray.{ArrayBuffer, Int8Array} + +trait XhrBackend extends Backend { + + def send(request: Request): Future[Response] = { + val promise = Promise[Response] + val xhr = new XMLHttpRequest() + + xhr.open(request.method, request.url) + xhr.responseType = "arraybuffer" + for ((name, value) <- request.headers) { + xhr.setRequestHeader(name, value) + } + + xhr.send(js.Array(request.body: _*)) + + xhr.onload = (e: Event) => { + val body: Array[Byte] = if (!js.isUndefined(xhr.response)) { + val buffer = new Int8Array(xhr.response.asInstanceOf[ArrayBuffer]) + buffer.toArray + } else { + Array.empty[Byte] + } + + val response = Response( + xhr.status, + Map.empty, + body + ) + promise.success(response) + } + + xhr.onerror = (e: ErrorEvent) => { + promise.failure(new RuntimeException(s"XHR error: ${e.message}")) + } + xhr.ontimeout = (e: Event) => { + promise.failure( + new TimeoutException(s"Request timed out: ${xhr.statusText}")) + } + + promise.future + } + +} -- cgit v1.2.3