Skip to main content
Version: 4.x.x

Data Mapping


Changing data before sending it to server

We often encounter the need to map data before sending data to server. This is usually required for two reasons.

One of them is breaking changes to the server api, which may require many updates to our existing code, which may be dangerous for the application and introduce regression.

Another case is sending FormData, which is impossible to represent in the form of an exact interface in terms of the fields it contains. In order not to send something that is equivalent to the type any, we can specify the correct type in the request and then map everything to FormData just before it gets added to Dispatcher.

This way, we ensure very type-safe and flexible development of our application.

Set payload data mapper

Below example show the implementation for FormData

export const postUserProfile = client
.createRequest<boolean, UserProfile>()({
method: "PATCH",
endpoint: "/users/profile/:userId",
})
.setDataMapper((data) => {
// Transform data:UserProfile into FormData
const formData = new FormData();

Object.entries(data).forEach(([key, value]) => {
formData.append(key, value);
});

// Return new data format
return formData;
});

Map whole request

Below example show the implementation of request mapping. We can make each postUserProfile request to add custom headers or any other value to the request before sending it later on when we use it in our application. This way we can implement mappers, validators and any async logic. Throwing an error makes request to return error just like we get it from the "real" query.

export const postUserProfile = client
.createRequest<boolean, UserProfile>()({
method: "PATCH",
endpoint: "/users/profile/:userId",
})
.setRequestMapper((request) => {
return request.setHeaders({ ...request.headers, "X-Better-Typed": "My custom header" });
});