diff --git a/src/ffi.mjs b/src/ffi.mjs index f0f4619..032bd6f 100644 --- a/src/ffi.mjs +++ b/src/ffi.mjs @@ -1,4 +1,4 @@ -import { Ok, Error, List } from "./gleam.mjs"; +import { Ok, Error, List, toBitArray } from "./gleam.mjs"; import { to_string as uri_to_string } from "../gleam_stdlib/gleam/uri.mjs"; import { method_to_string } from "../gleam_http/gleam/http.mjs"; import { to_uri } from "../gleam_http/gleam/http/request.mjs"; @@ -42,6 +42,16 @@ function make_headers(headersList) { return headers; } +export async function read_bytes_body(response) { + let body; + try { + body = await response.body.arrayBuffer() + } catch (error) { + return new Error(new UnableToReadBody()); + } + return new Ok(response.withFields({ body: toBitArray(new Uint8Array(body)) })); +} + export async function read_text_body(response) { let body; try { diff --git a/src/gleam/fetch.gleam b/src/gleam/fetch.gleam index 74d3838..4487f84 100644 --- a/src/gleam/fetch.gleam +++ b/src/gleam/fetch.gleam @@ -35,6 +35,11 @@ pub fn to_fetch_request(a: Request(String)) -> FetchRequest @external(javascript, "../ffi.mjs", "from_fetch_response") pub fn from_fetch_response(a: FetchResponse) -> Response(FetchBody) +@external(javascript, "../ffi.mjs", "read_bytes_body") +pub fn read_bytes_body( + a: Response(FetchBody), +) -> Promise(Result(Response(BitArray), FetchError)) + @external(javascript, "../ffi.mjs", "read_text_body") pub fn read_text_body( a: Response(FetchBody), diff --git a/test/gleam_fetch_test.gleam b/test/gleam_fetch_test.gleam index f3324bd..3e83ba7 100644 --- a/test/gleam_fetch_test.gleam +++ b/test/gleam_fetch_test.gleam @@ -17,6 +17,26 @@ pub fn request_test() { |> request.set_path("/hello/world") |> request.prepend_header("accept", "application/vnd.hmrc.1.0+json") + fetch.send(req) + |> promise.try_await(fetch.read_bytes_body) + |> promise.await(fn(resp: Result(Response(BitArray), FetchError)) { + let assert Ok(resp) = resp + let assert 200 = resp.status + let assert Ok("application/json") = + response.get_header(resp, "content-type") + let assert <<123, 34, 109, 101, 115, 115, 97, 103, 101, 34, 58, 34, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 34, 125>> = resp.body + promise.resolve(Ok(Nil)) + }) +} + +pub fn text_request_test() { + let req = + request.new() + |> request.set_method(Get) + |> request.set_host("test-api.service.hmrc.gov.uk") + |> request.set_path("/hello/world") + |> request.prepend_header("accept", "application/vnd.hmrc.1.0+json") + fetch.send(req) |> promise.try_await(fetch.read_text_body) |> promise.await(fn(resp: Result(Response(String), FetchError)) {