forked from cartesi/rollups-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
send-input.helpers.ts
45 lines (40 loc) · 1.59 KB
/
send-input.helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { SendInputData } from "../../../../controller/send.controller";
import { convertArrayBufferToBase64 } from "../../../../utils/array-buffer-to-base64-conversor";
import { GalleryItem } from "../biometrics-gallery/biometrics-gallery.board";
export const handleGalleryInput = async (
data: GalleryItem,
requestHandler: (
data: SendInputData,
shouldAvoidNotices: boolean
) => Promise<void>
) => {
const maxChunkLength = 50000;
const getImage = await fetch(data.imgUrl);
const result = await getImage.arrayBuffer();
const convertedResult = convertArrayBufferToBase64(result);
const chunksCount = Math.ceil(convertedResult.length / maxChunkLength);
let currentChunkStart = 0;
let currentChunkEnd = maxChunkLength;
for (let idx = 0; idx < chunksCount; idx++) {
const content = convertedResult.slice(
currentChunkStart,
currentChunkEnd
);
const isFirstIteration = idx === 0;
const isLastIteration = currentChunkEnd > convertedResult.length;
const sendInputData: SendInputData = {
chunk: isFirstIteration
? "initial"
: isLastIteration
? "final"
: idx + 1,
imageId: data.id,
content,
};
const shouldAvoidNotices = sendInputData.chunk !== "final";
await requestHandler(sendInputData, shouldAvoidNotices);
currentChunkStart = currentChunkEnd;
if (isLastIteration) currentChunkEnd = convertedResult.length;
else currentChunkEnd += maxChunkLength;
}
};