redux-toolkit
redux-toolkit copied to clipboard
how to write endpoints from emtpyApi for pass transformResponse or for add custom fn
Hi,
I try to generate endpoints from a openapi file, all is good but all my endpoint forward a x-total variable in the headers. I want retrieve this with a transformResponse():
transformResponse: (apiResponse, meta) => ({ apiResponse, total: Number(meta.response.headers.get('x-total')) }),
Buthow pass this fn in the emptyApi.ts file used by generator ?
My emptyfile.ts looks like
baseQuery: fetchBaseQuery({
baseUrl: Config.TOWER_URL + '/',
prepareHeaders: (headers, { getState }) => {
const token = (getState() as RootState).login.token;
if (token) {
headers.set('authorization', `Bearer ${token}`);
}
return headers;
},
}),
endpoints: (build) => {
return build.query({
transformResponse: (apiResponse, meta) => ({ apiResponse, total: Number(meta.response.headers.get('x-total')) }),
});
},
});```
Anybody can help me ?
Thank
Ok, i understand that i need t use enhanceEndpoints on my emptyApi.ts file export. But what it's the way to add transformResponse for all request ?
Thanks
You could wrap your baseQuery
in a custom function that modifies the result.
Hey, i find an other issue where you advice this. I try this way with in createApi
baseQuery(...args) {
const result = bq(...args);
if (result?.data) {
return { ...result, data: result.data.response, total: Number(result.meta?.response?.headers?.get('x-total')) };
}
return result;
},
where bq it's
const bq = fetchBaseQuery({
baseUrl: Config.URL + '/',
prepareHeaders: (headers, { getState }) => {
const token = (getState() as RootState).login.token;
if (token) {
headers.set('authorization', `Bearer ${token}`);
}
return headers;
},
but bq(...args) return either promise or data (if data is caching i purpose) so if(result?.data) doesn't exist yet on promise
If i async / await baseQuery() it's throw an error since baseQuery must return {data: YourData}
any advice ?
Thanks for your answer by the way
baseQuery
can also return a Promise<{data: YourData }>
, that should not throw any error.
you right, it's ok, i can return {data: {result:result.data, total : result.meta.header...} }, but result it's not really what i wish.
I wish add a total key on useGetCommentsQuery response like
const { data, total } = useGetCommentsQuery({
where total fill with repsonse.header
There are a way to do this ? :$
Thank
You can never add anything outside of data
, you'd have to add it inside of that.
ok, thank for your time