-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
39 lines (32 loc) · 1.29 KB
/
Copy pathclient.ts
File metadata and controls
39 lines (32 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* The typed RPC client over the network.
*
* bun run examples/client.ts
*/
import { Ma, mc } from "@ma/core"
import type { InferInput, InferOutput } from "@ma/core"
import { z } from "zod"
const app = new Ma()
.get("/hello/:name", (c) => ({ message: `Hello, ${c.params.name}!` }))
.get(
"/search",
{ query: z.object({ q: z.string(), limit: z.coerce.number().default(10) }) },
(c) => ({
query: c.query.q,
limit: c.query.limit,
}),
)
.post("/echo", { body: z.object({ value: z.string() }) }, (c) => ({ echoed: c.body.value }))
const server = Bun.serve({ port: 0, fetch: app.fetch })
const client = mc<typeof app>(server.url.href)
// Types flow end to end — hover any of these.
const hello = await client.hello[":name"].get({ name: "world" })
if (hello.ok) console.log(hello.data.message)
const search = await client.search.get({ query: { q: "ma", limit: 3 } })
console.log(search.data)
const echoed = await client.echo.post({ body: { value: "types!" } })
console.log(echoed.data)
// Extract types from the client when you need them elsewhere:
export type HelloResponse = InferOutput<(typeof client.hello)[":name"]["get"]> // { message: string }
export type EchoArgs = InferInput<typeof client.echo.post> // { body: { value: string }, headers?: ... }
server.stop()