Skip to main content
Version: v10.5.0

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.

What you'll learn
  1. How to reshape responses with setResponseMapper and keep the types.
  2. Why the cache keeps the raw response, and how to get several views of one entry.
  3. How to send a typed object as FormData with setPayloadMapper.
  4. 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.

src/api/users.ts
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.

src/api/users.ts
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.

src/api/profile.ts
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.

src/api/orders.ts
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:

src/api/sdk.ts
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 },
};
}),
});
MapperRunsChanges typesUse it for
setResponseMapperAfter the response, on every deliverydata and errorReshaping, models, validation
setPayloadMapperRight before sendingNoFormData, encoding
setRequestMapperRight before sendingNoPer-request headers, signing

Congratulations!

You've learned how to map data.

  • You can reshape responses with setResponseMapper and get typed data.
  • You can read several views of one cache entry, since the cache keeps raw data.
  • You can send typed objects as FormData with setPayloadMapper.
  • You can change a request before sending with setRequestMapper.

Runnable example: Response mapping.

Advanced mapping
Async mappers, class models and failing mappers.
Validation
Validate responses and payloads with Zod in mappers.
Request
Mappers and the other request methods.