Skip to main content
Version: v10.5.0

Mapping

Data mapping covers reshaping a response and sending FormData. This guide goes further: async mappers that enrich a response, class models, what happens when a mapper throws, and where each mapper runs in the request's life.

What you'll learn
  1. How to write async mappers that enrich a response.
  2. How to hydrate class models from the response.
  3. What happens when a mapper throws.
  4. The order in which interceptors and mappers run.

Enrich a response with an async mapper​

Mappers can return a promise. Here the mapper turns a date string into a Date and adds the user's teams from a second request. send() resolves after the mapper finishes.

src/api/users.ts
type UserModel = { id: number; name: string; createdAt: string };

const getTeams = client.createRequest<{
response: { id: number; name: string }[];
}>()({
endpoint: "/users/:userId/teams",
});

export const getUser = client
.createRequest<{ response: UserModel }>()({ endpoint: "/users/:userId" })
.setResponseMapper(async (response) => {
if (!response.data) return response;

const { data: teams } = await getTeams.send({
params: { userId: response.data.id },
});

return {
...response,
data: {
...response.data,
createdAt: new Date(response.data.createdAt),
teams: teams ?? [],
},
};
});

The mapper runs on every delivery of the response, including reads from the cache by hooks. Keep extra requests cheap, or let the second request's own cache absorb repeated calls.


Hydrate class models​

Return an instance instead of a plain object to give the data methods and computed fields. The cache keeps the raw object, so it stays serializable for persistence and hydration.

src/models/user.ts
export class User {
id: number;
name: string;
createdAt: Date;

constructor(data: UserModel) {
this.id = data.id;
this.name = data.name;
this.createdAt = new Date(data.createdAt);
}

get memberSince() {
return this.createdAt.getFullYear();
}
}

export const getUserModel = client
.createRequest<{ response: UserModel }>()({ endpoint: "/users/:userId" })
.setResponseMapper((response) => {
if (!response.data) return response;
return { ...response, data: new User(response.data) };
});

Each delivery creates a new instance, so compare models by id, not by reference.


When a mapper throws​

A response mapper that throws, or whose promise rejects, turns the response into a failure. send() still resolves with success: false, data: null and the thrown value in error. The client logger reports it, hooks call their error callbacks and an optimistic update rolls back.

src/api/users.ts
const getCheckedUser = client
.createRequest<{ response: UserModel }>()({ endpoint: "/users/:userId" })
.setResponseMapper((response) => {
if (response.data && typeof response.data.name !== "string")
throw new Error("Invalid user");
return response;
});

const { success, error } = await getCheckedUser.send({ params: { userId: 1 } });
// success: false, error: Error("Invalid user")

A request mapper or payload mapper that throws stops the request before it is sent, and error holds the thrown value. Validation builds on this.


The order of mappers​

Each send() goes through these steps. Client-wide steps come first, the request's own mappers after them.

StepRunsScope
1client.onRequest interceptorsEvery request
2client.onAuth interceptors, when auth is onEvery request
3setRequestMapperThis request
4setPayloadMapper, or the adapter's payload mapperThis request
5The adapter sends the request
6client.onResponse, then onSuccess or onErrorEvery request
7The response is written to the cache, unmapped
8setResponseMapperThis request

So a request mapper sees the auth headers, and a response mapper sees what the response interceptors returned.

src/api/files.ts
// Request mappers can also be async, for example to sign the final request
export const uploadFile = client
.createRequest<{ response: { url: string }; payload: Blob }>()({
endpoint: "/files",
method: "PUT",
})
.setRequestMapper(async (request) => {
const signature = await sign(request.endpoint);
return request.setHeaders({ ...request.headers, "X-Signature": signature });
});

Congratulations!

You've learned the advanced side of mapping.

  • You can write async mappers that enrich responses.
  • You can hydrate class models while the cache keeps raw data.
  • You know that a throwing mapper gives an error response instead of a rejected promise.
  • You know the order of interceptors and mappers.

Runnable examples: Response mapping and Payload validation.

Validation
Validate data with Zod inside mappers.
Intercepting
Client-wide request and response interceptors.
Request API reference
setResponseMapper, setRequestMapper and setPayloadMapper.