Skip to content

Commit a9a3b5e

Browse files
delventhalzZac Delventhaljasonsaayman
authored
Fixing default transformRequest with buffer pools (axios#1511)
* Fixing default transformRequest of TypedArrays with buffer pools A buffer pool is a large ArrayBuffer of a preset size used with a TypedArray such as Uint8Array. This can speed up performance when constructing TypedArrays of unknown sizes, and is a technique used by Node with their Buffers, and by libraries like dcodeIO/protobuf.js. Because the ArrayBuffer of such a TypedArray is much longer than the array itself, using `.buffer` to transform the array before POSTing results in sending a request with many extraneous empty bytes, which is wastefule and may result in unexpected behavior. Using `.slice()` before grabbing the ArrayBuffer fixes the problem by creating a new TypedArray with a buffer of the expected length. Signed-off-by: Zac Delventhal <[email protected]> * Adding test for using default transformRequest with buffer pools Adds a new test to the default transformRequest, running it on a Uint8Array with a byte length of 16, but a much larger ArrayBuffer with a byte length of 256. The transformed array should not include any extra bytes, and so must have a byte length of just 16. Signed-off-by: Zac Delventhal <[email protected]> Co-authored-by: Zac Delventhal <[email protected]> Co-authored-by: Jay <[email protected]>
1 parent 8a8c534 commit a9a3b5e

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

lib/defaults.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ var defaults = {
4141
return data;
4242
}
4343
if (utils.isArrayBufferView(data)) {
44-
return data.buffer;
44+
return data.slice().buffer;
4545
}
4646
if (utils.isURLSearchParams(data)) {
4747
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');

test/specs/defaults.spec.js

+6
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ describe('defaults', function () {
2424
expect(defaults.transformRequest[0]('foo=bar')).toEqual('foo=bar');
2525
});
2626

27+
it('should transform TypedArrays without including buffer pool', function () {
28+
if (typeof Uint8Array === 'undefined') return this.skip();
29+
const buffered = new Uint8Array(256).subarray(10, 26);
30+
expect(defaults.transformRequest[0](buffered).byteLength).toEqual(16);
31+
});
32+
2733
it('should transform response json', function () {
2834
var data = defaults.transformResponse[0]('{"foo":"bar"}');
2935

0 commit comments

Comments
 (0)