Welcome to the new Golem Cloud Docs! 👋
Documentation
Experimental Languages
TypeScript
HTTP client

HTTP requests in TypeScript

⚠️

Currently HTTP and fetch support is experimental. The Golem TypeScript SDK has temporary workarounds to make HTTP requests possible, but bugs and breaking changes are expected in this area.

Golem implements the WASI HTTP (opens in a new tab) interfaces so any library built on this specification can be used from Golem components to communicate with external services.

HTTP request can be made with the JavaScript standard builtin fetch function, but handling the asynchronous return values inside the synchronous component functions requires helpers from the Golem TypeScript SDK.

The SDK (opens in a new tab) provides asyncToSync and asyncToSyncAsResult functions to wait for Promises.

The asyncToSync function throws exceptions in case the Promise is failed, while the asyncToSyncAsResult returns a Result<T, E> type, which is defined in the SDK (opens in a new tab).

import { asyncToSync, asyncToSyncAsResult, Result } from "@golemcloud/golem-ts"
 
// Using asyncToSyncAsResult to await for fetch results as Result
const result: Result<string> = asyncToSyncAsResult(
  fetch("https://localhost:8080").then(result => result.text())
)
 
const text = result.match(
  text => text,
  err => {
    console.error(err)
    return "failed"
  }
)
 
// Using asyncToSync to await for fetch results which might throw exceptions in case of errors
try {
  const text = asyncToSync(fetch("https://localhost:8080").then(result => result.text()))
} catch (err) {
  console.log(err)
}