Service bindings
On the cloudflare preset one Worker can call another without a public request, through a service binding. In Hamur the binding is a createFetch option: createFetch({ binding: "API" }) makes a client whose / URLs call env.API.fetch.
Declare the binding
Add the other Worker to services of your wrangler config:
{
"name": "my-web",
"services": [{ "binding": "API", "service": "my-api" }],
}
With a wrangler config in the app, hamur typegen types env.API as a fetcher (services maps to HamurFetcher, see Dev bindings and typed env), and hamur dev runs it through the local bindings.
Call it
The client takes the other app's route table as its type argument, so a literal URL has its body and query checked and its data typed:
import { createFetch } from "hamur/server"
// The other app's table, as its .hamur/types/fetch-routes.d.ts exports it:
// type ApiRoutes = import("../api/.hamur/types/fetch-routes").HamurAppRoutes
interface ApiRoutes {
static: {
"/api/users": {
GET: { data: Array<{ id: number; name: string }>; input: unknown; key: "query"; events: unknown }
POST: { data: { id: number }; input: { name: string }; key: "body"; events: unknown }
}
}
dynamic: []
}
const api = createFetch<ApiRoutes>({ binding: "API" })
export async function addUser(name: string, token: string) {
const users = await api("/api/users")
const created = await api("/api/users", {
method: "POST",
body: { name },
headers: { authorization: `Bearer ${token}` },
})
// @ts-expect-error the route's body is { name: string }
await api("/api/users", { method: "POST", body: { name: 1 } })
return { count: users.length, id: created.id }
}
The type argument is the route table hamur typegen wrote for the other app as HamurAppRoutes in its .hamur/types/fetch-routes.d.ts; the sample spells the same table out so it stands alone. The headers that are not forwarded (cookie and authorization), the request's host, retry, and the errors for a missing binding or another preset are in Call another Worker. binding is an option of createFetch from hamur/server only.