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
let res = new Uint8Array ( 0 ) ;
21
14
const reader = stream . getReader ( ) ;
@@ -32,26 +25,3 @@ async function collectStream(stream: ReadableStream): Promise<Uint8Array> {
32
25
}
33
26
return res ;
34
27
}
35
-
36
- function readToBase64 ( blob : Blob ) : Promise < string > {
37
- return new Promise ( ( resolve , reject ) => {
38
- const reader = new FileReader ( ) ;
39
- reader . onloadend = ( ) => {
40
- // reference: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
41
- // response from readAsDataURL is always prepended with "data:*/*;base64,"
42
- if ( reader . readyState !== 2 ) {
43
- return reject ( new Error ( "Reader aborted too early" ) ) ;
44
- }
45
- const result = ( reader . result ?? "" ) as string ;
46
- // Response can include only 'data:' for empty blob, return empty string in this case.
47
- // Otherwise, return the string after ','
48
- const commaIndex = result . indexOf ( "," ) ;
49
- const dataOffset = commaIndex > - 1 ? commaIndex + 1 : result . length ;
50
- resolve ( result . substring ( dataOffset ) ) ;
51
- } ;
52
- reader . onabort = ( ) => reject ( new Error ( "Read aborted" ) ) ;
53
- reader . onerror = ( ) => reject ( reader . error ) ;
54
- // reader.readAsArrayBuffer is not always available
55
- reader . readAsDataURL ( blob ) ;
56
- } ) ;
57
- }
0 commit comments