restful.js
restful.js copied to clipboard
addResponseInterceptor doesn't alter data
My backend returns colections and items in objects with a collection key (e.g. {books: [...]}).
I can't configure restful.js to handle this (BTW this should be possible, keyed responses are a standart), so I've tried to add Response Interceptorto alter data manually. But it simply doesn't work: it gets data, I can use it, but in subsequent code I keep seeing original data.
import restful, {fetchBackend} from 'restful.js';
const api = restful('//' + window.location.host + '/api', fetchBackend(fetch));
api.addRequestInterceptor(function (request) {
return {
headers: Object.assign({}, request.headers, {'Content-Type': 'application/json'})
}
});
api.addResponseInterceptor(function(response, config){
let { data, headers, statusCode } = response;
data = data[Object.keys(data)[0]];
return {
data
};
});
export default api;
+1
I don't understand the syntax of the response interceptor you posted, is it just es6?
return {
data: response.data[Object.keys(response.data)[0]]
};
should work, if you figure out how this works differently from what you posted we should put a note in the docs.
What I see is that its merging my modified items into the original structure somehow.
from the addResponseInterceptor call, I do the following
return {
data: RestClientData(data);
}
The result of RestClientData(data) as an example, is as follows:
Object{
limit:20
list:Array[20]
test:"hello world"
total:81
}
However, in the promise then callback, I console.log dump the response.body().data() and I get
Object {
_embedded: Object
_links:Object
limit:20
list:Array[20]
test:"hello world"
total:81
}
where _embedded and _links are from the original response that I intercepted and passed into RestClientData(data) function call.
So, it appears to be merging the returned data structure, with the one it already had. This isn't really desired behaviour, but perhaps its a way to deal with chaining multiple response interceptors?
But in this case, perhaps the solution is that each subsequent interceptor receives the data structure from the previously executed one?
Any update on this? This is still an issue.
I have the same issue I tried with:
return {
data: []
}
for seeing if the data is altered but it does not work.
I have the same issue:
I get Expected array as response, you should use one method for that on each getAll() call.
I can use my collection by calling reponse.collection but there should be a way to avoid this warning ...