Data mapping
The shape your API returns is rarely the shape your UI wants: nested envelopes, snake_case fields, ISO date strings.
Mappers transform data at the edge of a request, so components only see your app's models. This guide covers response,
payload and request mappers and how they interact with the cache.
- How to reshape responses with
setResponseMapperand keep the types. - Why the cache keeps the raw response, and how to get several views of one entry.
- How to send a typed object as
FormDatawithsetPayloadMapper. - How to change the request itself with
setRequestMapper.
Reshape the response
setResponseMapper receives the whole response and returns a whole response. Map data and keep the rest, and return
failed responses as they are. The type of data follows what the mapper returns.
type ApiUser = { id: number; user_name: string; is_active: boolean };
type User = { id: number; name: string; isActive: boolean };
export const getUser = client
.createRequest<{ response: { data: ApiUser } }>()({
endpoint: "/users/:userId",
})
.setResponseMapper((response) => {
if (!response.data) return response;
const { id, user_name, is_active } = response.data.data;
return {
...response,
data: { id, name: user_name, isActive: is_active } satisfies User,
};
});
const { data } = await getUser.send({ params: { userId: 1 } });
// data: User | null
Return the response object, not bare data. Returning response.data.data alone would replace the response and lose
status, error and extra.
Several views of one cache entry
The cache stores the raw adapter response, and each request runs its own mapper on delivery. Requests with different mappers but the same endpoint share one cache entry and deduplicate with each other.
const getUserRaw = client.createRequest<{ response: ApiUser }>()({
endpoint: "/users/:userId",
});
// Same cacheKey, different shapes
export const getUserName = getUserRaw.setResponseMapper((response) => {
if (!response.data) return response;
return { ...response, data: response.data.user_name };
});
export const getUserStatus = getUserRaw.setResponseMapper((response) => {
if (!response.data) return response;
return { ...response, data: { active: response.data.is_active } };
});
Because the cache holds raw data, client.cache.update and request.read() work with the API shape, not the mapped one.
Send a typed object as FormData
setPayloadMapper transforms the payload right before it is sent. Callers pass a typed object, the server receives
FormData.
export const updateProfile = client
.createRequest<{
response: User;
payload: { username: string; avatar: File };
}>()({
endpoint: "/profile",
method: "POST",
})
.setPayloadMapper(({ username, avatar }) => {
const formData = new FormData();
formData.append("username", username);
formData.append("avatar", avatar);
return formData;
});
await updateProfile.send({ payload: { username: "ann", avatar: file } });
The payload type stays the object, so callers are still checked. See payload.
Change the request before it is sent
setRequestMapper receives the request and its requestId right before sending and returns a request, built with the
usual setters. It runs after the client's onRequest and onAuth interceptors, only for this request.
export const createOrder = client
.createRequest<{ response: Order; payload: OrderInput }>()({
endpoint: "/orders",
method: "POST",
})
// A stable key per call, so the server can drop duplicates of a retried order
.setRequestMapper((request, requestId) =>
request.setHeaders({ ...request.headers, "Idempotency-Key": requestId }),
);
For changes that apply to every request, use interceptors on the client.
Map every SDK endpoint in one place
With an SDK, set mappers per endpoint in $configure instead of on each request:
export const api = sdk.$configure({
"users.$userId.$get": (request) =>
request.setResponseMapper((response) => {
// Leaves are typed loosely here, so narrow on success
if (!response.success) return response;
return {
...response,
data: { id: response.data.id, name: response.data.user_name },
};
}),
});
| Mapper | Runs | Changes types | Use it for |
|---|---|---|---|
setResponseMapper | After the response, on every delivery | data and error | Reshaping, models, validation |
setPayloadMapper | Right before sending | No | FormData, encoding |
setRequestMapper | Right before sending | No | Per-request headers, signing |
You've learned how to map data.
- You can reshape responses with
setResponseMapperand get typeddata. - You can read several views of one cache entry, since the cache keeps raw data.
- You can send typed objects as
FormDatawithsetPayloadMapper. - You can change a request before sending with
setRequestMapper.
Runnable example: Response mapping.