Skip to content

Commit b737b59

Browse files
committed
minimalistic transformResponse for json response type
1 parent 982fd7f commit b737b59

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/index.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,19 @@ export default (function create(defaults) {
119119
return overrides;
120120
}
121121

122+
/**
123+
* @private
124+
*/
125+
function transformResponse(data) {
126+
if (typeof data === 'string') {
127+
try {
128+
data = JSON.parse(data);
129+
}
130+
catch (e) {}
131+
}
132+
return data;
133+
}
134+
122135
/**
123136
* Issues a request.
124137
* @public
@@ -184,7 +197,7 @@ export default (function create(defaults) {
184197
? Promise.resolve(res.body)
185198
: res[options.responseType || 'text']();
186199
return withData.then((data) => {
187-
response.data = data;
200+
response.data = transformResponse(data);
188201
return response;
189202
});
190203
});

test/index.test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,15 @@ describe('redaxios', () => {
5050
expect(res.data).toEqual({ hello: 'world' });
5151
});
5252

53+
it('response should be parsed json', async () => {
54+
const req = axios.get(jsonExample);
55+
expect(req).toBeInstanceOf(Promise);
56+
const res = await req;
57+
expect(res).toBeInstanceOf(Object);
58+
expect(res.status).toEqual(200);
59+
expect(res.data).toBeInstanceOf(Object);
60+
});
61+
5362
it('should issue POST requests', async () => {
5463
const oldFetch = window.fetch;
5564
try {

0 commit comments

Comments
 (0)