From 65a36581db0279a6044fd815201f91bcab4dcf90 Mon Sep 17 00:00:00 2001 From: tkashi Date: Tue, 28 Apr 2020 09:52:30 +0900 Subject: [PATCH] fix(util-body-length-browser): multi-byte body lengths for browser (#1101) --- .../src/index.spec.ts | 23 +++++++++++++++++++ .../util-body-length-browser/src/index.ts | 2 +- .../util-body-length-browser/tsconfig.json | 3 ++- 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 packages/util-body-length-browser/src/index.spec.ts diff --git a/packages/util-body-length-browser/src/index.spec.ts b/packages/util-body-length-browser/src/index.spec.ts new file mode 100644 index 000000000000..1fb4c5d3e56f --- /dev/null +++ b/packages/util-body-length-browser/src/index.spec.ts @@ -0,0 +1,23 @@ +import { calculateBodyLength } from "./"; + +const arrayBuffer = new ArrayBuffer(1); +const typedArray = new Uint8Array(1); +const view = new DataView(arrayBuffer); + +describe("caclulateBodyLength", () => { + it("should handle string inputs", () => { + expect(calculateBodyLength("foo")).toEqual(3); + }); + + it("should handle string inputs with multi-byte characters", () => { + expect(calculateBodyLength("2。")).toEqual(4); + }); + + it("should handle inputs with byteLengths", () => { + expect(calculateBodyLength(arrayBuffer)).toEqual(1); + }); + + it("should handle TypedArray inputs", () => { + expect(calculateBodyLength(typedArray)).toEqual(1); + }); +}); diff --git a/packages/util-body-length-browser/src/index.ts b/packages/util-body-length-browser/src/index.ts index 5daf1ef3617e..3ab61ebf1e63 100644 --- a/packages/util-body-length-browser/src/index.ts +++ b/packages/util-body-length-browser/src/index.ts @@ -1,6 +1,6 @@ export function calculateBodyLength(body: any): number | undefined { if (typeof body === "string") { - return body.length; + return new Blob([body]).size; } else if (typeof body.byteLength === "number") { // handles Uint8Array, ArrayBuffer, Buffer, and ArrayBufferView return body.byteLength; diff --git a/packages/util-body-length-browser/tsconfig.json b/packages/util-body-length-browser/tsconfig.json index ea8af8858555..4fe7c1e7a45f 100644 --- a/packages/util-body-length-browser/tsconfig.json +++ b/packages/util-body-length-browser/tsconfig.json @@ -11,7 +11,8 @@ "es2015.promise", "es2015.collection", "es2015.iterable", - "es2015.symbol.wellknown" + "es2015.symbol.wellknown", + "dom" ], "rootDir": "./src", "outDir": "./build",