forked from aws-amplify/amplify-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(@aws-amplify/interactions): remove
Readable
dependencies (aws-a…
- Loading branch information
Showing
2 changed files
with
28 additions
and
59 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
43 changes: 7 additions & 36 deletions
43
packages/interactions/src/Providers/AWSLexProviderHelper/convert.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,41 +1,12 @@ | ||
import { Readable } from 'stream'; | ||
export const convert = async ( | ||
stream: Readable | ReadableStream | Blob | ||
export const convert = ( | ||
stream: Blob | Readable | ReadableStream | ||
): Promise<Uint8Array> => { | ||
if (stream instanceof Readable) { | ||
return readOnNode(stream); | ||
if (stream instanceof Blob || stream instanceof ReadableStream) { | ||
return new Response(stream) | ||
.arrayBuffer() | ||
.then(buffer => new Uint8Array(buffer)); | ||
} else { | ||
return readOnBrowser(stream); | ||
throw new Error('Readable is not supported.'); | ||
} | ||
}; | ||
|
||
const readOnBrowser = (stream: ReadableStream | Blob) => { | ||
return new Response(stream) | ||
.arrayBuffer() | ||
.then(buffer => new Uint8Array(buffer)); | ||
}; | ||
|
||
const readOnNode = (stream: Readable): Promise<Uint8Array> => { | ||
if (!stream.isPaused()) stream.pause(); | ||
const chunks: Array<string | Buffer> = []; | ||
return new Promise((res, rej) => { | ||
stream.on('readable', () => { | ||
while (true) { | ||
const chunk = stream.read(); | ||
if (!chunk) break; | ||
chunks.push(chunk); | ||
} | ||
}); | ||
stream.on('end', () => { | ||
const blob = new Blob(chunks); | ||
const fileReader = new FileReader(); | ||
fileReader.onload = event => { | ||
const buffer = event.target.result as ArrayBuffer; | ||
return res(new Uint8Array(buffer)); | ||
}; | ||
fileReader.onerror = rej; | ||
fileReader.readAsArrayBuffer(blob); | ||
}); | ||
stream.on('error', rej); | ||
}); | ||
}; |