The dashboard client
Generate a typed TypeScript client, zod schemas and an OpenAPI document from the backend, so the dashboard and backend can't drift.
The backend writes its dashboard's client from what it registered: every route with its parameters, body and answer, every realtime channel with its message type, and every permission. At the end of this guide your dashboard calls the backend through floor.gen.ts, and renaming a field in Rust makes tsc fail at each place the dashboard reads it. You need a backend whose route types derive floor::Type, and a dashboard in TypeScript (the gate keeps it in web/).
1. Describe the types
Every type a route takes or returns, and every channel message, derives floor::Type next to serde:
use floor::prelude::*;
#[derive(Serialize, Deserialize, sqlx::FromRow, Type)]
pub struct Visit {
pub id: i64,
pub plate: String,
pub vehicle_id: Option<i64>,
pub lane_id: i64,
pub status: String,
pub entry_ms: Option<i64>,
}Json<T>, Query<T>, Path<T>, Created<T> and channel messages require it, so a type you forget is a compile error, not a gap in the client.
2. Generate the files
The backend's own binary writes them. From the crate's folder:
cargo run -- --ts web/src/floor.gen.ts --zod web/src/floor.zod.ts --openapi web/openapi.json| Flag | Writes |
|---|---|
--ts <file> | The typed client |
--zod <file> | A zod schema per type, typed against the client |
--zod-client <path> | The import path from the zod file to the client (default ./floor.gen) |
--openapi <file> | An OpenAPI 3.1 document |
The binary writes the files and exits; it doesn't start the backend. If a check fails (a can that permissions.rs doesn't define, two types with one name), it says so and writes nothing.
While you edit, floor dev rewrites the client on every save: to web/src/floor.gen.ts when web/ exists, or to --ts <file>. It rewrites floor.zod.ts too when that file is already there. The gate commits the generated files, so its dashboard builds without building the backend.
3. Configure and call
import { api, configure } from './floor.gen'
configure({ token: () => auth.accessToken() }) // createAuth from @usefloor/floor (Sign-in)
const page = await api.visits.get({ limit: 20 }) // Visits
const visit = await api.visits.$id.get(42) // Visit
const car = await api.vehicles.post({ plate: 'LEB-4821' }) // Vehicle
const { command } = await api.gates.$lane.open.post(1) // Opened- Routes are
api.<path>.<method>. A path parameter is a$namelevel:/api/gates/{lane}/openisapi.gates.$lane.open. - A method takes the path parameters first, then the body or the query, then options (
signal,headers). A query whose fields are all optional may be left out. - It returns the route's answer type:
Json<T>andCreated<T>giveT, aStringroute givesstring,NoContentgives nothing. configuretakestoken(a function, so a fresh token is read for each call),baseUrl(default'', the same origin),fetchandheaders.
Serve the backend under the dashboard's hostname (access-control.example.com/api) and the same origin works with no CORS. While you develop, point Vite's proxy at floor dev's backend:
// vite.config.ts
export default defineConfig({
server: { proxy: { '/api': process.env.FLOOR_BACKEND ?? 'http://127.0.0.1:3000' } },
})floor dev --web runs the dashboard's dev server too, with FLOOR_BACKEND set.
4. Handle errors
A call that doesn't succeed throws ApiError, with status, the backend's message and the body:
import { ApiError } from './floor.gen'
try {
await api.vehicles.post({ plate })
} catch (e) {
if (e instanceof ApiError && e.status === 409) showError('That plate is registered already')
else throw e
}5. Listen and check permissions
The client carries the backend's channels and permissions:
import { can, channels, listen } from './floor.gen'
const sub = listen(floor.realtime, channels.lanes, (card) => showCard(card.plate, card.action)) // card: LaneCard
if (can(user, 'gates:open')) showOpenButton() // 'gates:close' is a type error
sub.close()channelsmaps each channel to itsapp:name and message type.listentakes@usefloor/floor'sfloor.realtime, or anything with the samesubscribe.candecides as the backend does, frompermissions.rs;permissionsand thePermissiontype are exported too.
6. Check data with zod
floor.zod.ts has a schema per type, named <Type>Schema:
import { VisitSchema } from './floor.zod'
const visit = VisitSchema.parse(JSON.parse(cached)) // Visit, or a ZodErrorUse it where data comes from somewhere the type system can't see: local storage, a URL, a message from another app.
7. Use the OpenAPI document
openapi.json describes every route with its parameters, body and answer as JSON Schema, and each route's auth as x-floor-auth ("public", "signed_in", {"roles": […]}, {"can": "…"} or "device"). Hand it to tools that read OpenAPI, or to people outside the team.
How Rust types become TypeScript
The shape follows serde, so the client sees what the backend sends:
- Supported serde attributes:
rename,rename_all,tag,content,untagged,default,skipandskip_serializing_if. Option<T>becomesname?: T | null. A field with#[serde(default)]orskip_serializing_ifis optional too.- Scalars: integers and floats are
number,boolisboolean, andString,charanduuid::Uuidarestring.serde_json::Valueisunknown. - Collections:
Vec<T>, sets and arrays are lists; maps with string keys are objects; tuples are tuples. - A field written by custom serde code (
with,serialize_with), or of a typefloor::Typedoesn't know (a timestamp type, say), says its shape:#[floor(as = "string")], ornumber,integer,boolean,any. - Two types with the same name in different modules are an error; rename one for the client with
#[floor(rename = "LaneVisit")]on the type. - Not described yet: generic types and
#[serde(flatten)]. The derive says so at compile time.
#[derive(Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct LaneStatus {
pub lane_id: i64, // laneId: number
#[serde(with = "time::serde::rfc3339")]
#[floor(as = "string")]
pub since: time::OffsetDateTime, // since: string, written by time's serde code
#[serde(skip_serializing_if = "Option::is_none")]
pub last_plate: Option<String>, // lastPlate?: string | null
}