1
1
import { StreamCollector } from "@smithy/types" ;
2
- import { fromBase64 } from "@smithy/util-base64" ;
3
2
4
3
//reference: https://snack.expo.io/r1JCSWRGU
5
4
export const streamCollector : StreamCollector = ( stream : Blob | ReadableStream ) : Promise < Uint8Array > => {
6
5
if ( typeof Blob === "function" && stream instanceof Blob ) {
7
- return collectBlob ( stream ) ;
6
+ return new Uint8Array ( await stream . arrayBuffer ( ) ) ;
8
7
}
9
8
10
9
return collectStream ( stream as ReadableStream ) ;
11
10
} ;
12
11
13
- async function collectBlob ( blob : Blob ) : Promise < Uint8Array > {
14
- const base64 = await readToBase64 ( blob ) ;
15
- const arrayBuffer = fromBase64 ( base64 ) ;
16
- return new Uint8Array ( arrayBuffer ) ;
17
- }
18
-
19
12
async function collectStream ( stream : ReadableStream ) : Promise < Uint8Array > {
20
13
const chunks = [ ] ;
21
14
const reader = stream . getReader ( ) ;
@@ -40,26 +33,3 @@ async function collectStream(stream: ReadableStream): Promise<Uint8Array> {
40
33
41
34
return collected ;
42
35
}
43
-
44
- function readToBase64 ( blob : Blob ) : Promise < string > {
45
- return new Promise ( ( resolve , reject ) => {
46
- const reader = new FileReader ( ) ;
47
- reader . onloadend = ( ) => {
48
- // reference: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
49
- // response from readAsDataURL is always prepended with "data:*/*;base64,"
50
- if ( reader . readyState !== 2 ) {
51
- return reject ( new Error ( "Reader aborted too early" ) ) ;
52
- }
53
- const result = ( reader . result ?? "" ) as string ;
54
- // Response can include only 'data:' for empty blob, return empty string in this case.
55
- // Otherwise, return the string after ','
56
- const commaIndex = result . indexOf ( "," ) ;
57
- const dataOffset = commaIndex > - 1 ? commaIndex + 1 : result . length ;
58
- resolve ( result . substring ( dataOffset ) ) ;
59
- } ;
60
- reader . onabort = ( ) => reject ( new Error ( "Read aborted" ) ) ;
61
- reader . onerror = ( ) => reject ( reader . error ) ;
62
- // reader.readAsArrayBuffer is not always available
63
- reader . readAsDataURL ( blob ) ;
64
- } ) ;
65
- }
0 commit comments