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.
- How to write async mappers that enrich a response.
- How to hydrate class models from the response.
- What happens when a mapper throws.
- 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.
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.
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.
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.
| Step | Runs | Scope |
|---|---|---|
| 1 | client.onRequest interceptors | Every request |
| 2 | client.onAuth interceptors, when auth is on | Every request |
| 3 | setRequestMapper | This request |
| 4 | setPayloadMapper, or the adapter's payload mapper | This request |
| 5 | The adapter sends the request | |
| 6 | client.onResponse, then onSuccess or onError | Every request |
| 7 | The response is written to the cache, unmapped | |
| 8 | setResponseMapper | This request |
So a request mapper sees the auth headers, and a response mapper sees what the response interceptors returned.
// 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 });
});
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.