From 8ecae787ff7124b008229d958c579c73649dd9e4 Mon Sep 17 00:00:00 2001 From: Jakob Odersky Date: Sun, 6 May 2018 13:56:16 -0700 Subject: Initial commit --- common/js/src/main/scala/http/XhrBackend.scala | 51 ++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 common/js/src/main/scala/http/XhrBackend.scala (limited to 'common/js/src/main/scala/http/XhrBackend.scala') diff --git a/common/js/src/main/scala/http/XhrBackend.scala b/common/js/src/main/scala/http/XhrBackend.scala new file mode 100644 index 0000000..3a791c1 --- /dev/null +++ b/common/js/src/main/scala/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