rays/fetch
Send HTTP requests from a Worker, to another Worker through a
service binding
or to the internet with the global fetch.
Requests are gleam_http requests with a worker.Body, the same body
type used to build responses. Responses come back with a ResponseBody
that is not read until you ask for it, so a response from another Worker
can be passed on to the client without buffering it, using forward.
import gleam/http/request
import gleam/javascript/promise.{type Promise}
import gleam/result
import rays/fetch
import rays/worker.{type Env, type Response}
// Ask the Worker bound as `AUTH` who the user is, and pass its answer on.
fn whoami(env: Env) -> Promise(Response) {
case fetch.service(env, "AUTH") {
Error(_) -> promise.resolve(worker.internal_server_error())
Ok(auth) -> {
let request =
request.new()
|> request.set_path("/whoami")
|> request.set_body(worker.Empty)
use result <- promise.map(fetch.send(request, to: auth))
case result {
Ok(response) ->
fetch.forward(response)
|> result.unwrap(worker.internal_server_error())
Error(_) -> worker.response(502)
}
}
}
}
A service binding ignores the request’s host, so the default localhost
from request.new is fine. A request sent with global goes to the
request’s scheme, host, and port.
Types
The body of a response received with send.
The body is not read until a function such as read_text or forward is
called, and it can only be read once.
pub opaque type ResponseBody
An error that can occur when sending a request.
pub type SendError {
InvalidRequest(message: String)
NetworkError(message: String)
Unknown(message: String)
}
Constructors
-
InvalidRequest(message: String)The request could not be built, for example because its URL is invalid, a
GETrequest has a body, or aBytesbody is not a whole number of bytes. This is usually a bug in the code building the request. -
NetworkError(message: String)The request could not be sent or no response was received, for example because the host could not be reached. Retrying may succeed.
-
Unknown(message: String)The runtime failed in some other way. The message is its error message.
Values
pub fn forward(
response: response.Response(ResponseBody),
) -> Result(response.Response(worker.Body), worker.BodyError)
Turn a received response into a response for the client, with the same status and headers. The body is streamed through without being read into memory.
Returns BodyAlreadyRead if the body has already been read.
Examples
use result <- promise.map(fetch.send(request, to: api))
case result {
Ok(response) ->
fetch.forward(response)
|> result.unwrap(worker.internal_server_error())
Error(_) -> worker.response(502)
}
pub fn global() -> Target
Send requests to the internet, with the Workers runtime’s global fetch.
pub fn read_bits(
response: response.Response(ResponseBody),
) -> promise.Promise(Result(BitArray, worker.BodyError))
Read the entire response body as a bit array. A response without a body gives an empty bit array.
Returns BodyAlreadyRead if the body has already been read, and
BodyReadFailed if it could not be read.
pub fn read_text(
response: response.Response(ResponseBody),
) -> promise.Promise(Result(String, worker.BodyError))
Read the entire response body as a UTF-8 string.
Returns the same errors as read_bits, and InvalidUtf8 if the body is
not valid UTF-8.
pub fn send(
request: request.Request(worker.Body),
to target: Target,
) -> promise.Promise(
Result(response.Response(ResponseBody), SendError),
)
Send a request and wait for the response’s status and headers. The
response body is not read until you call a function such as read_text
or forward.
A response with an error status such as 404 or 500 is still Ok: the
error is only for requests that got no response at all.
Examples
let request =
request.new()
|> request.set_path("/users/1")
|> request.set_body(worker.Empty)
use result <- promise.await(fetch.send(request, to: api))
pub fn service(
env: worker.Env,
name: String,
) -> Result(Target, Nil)
Send requests to the Worker bound to the given name, through a service binding.
Returns an error if there is no binding with that name, or if the binding is not a service binding, for example because it is a KV namespace.
Examples
case fetch.service(env, "AUTH") {
Ok(auth) -> todo
Error(_) -> worker.internal_server_error() |> promise.resolve
}