Skip to content

Commit

Permalink
refactor: reuse async iterators..
Browse files Browse the repository at this point in the history
  • Loading branch information
Myphz committed Jan 2, 2024
1 parent 8c58d6f commit 2b592a1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/routes/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { FastifyPluginCallback } from "fastify";
import multipart from "@fastify/multipart";
import { getFileDownload, getFileLink, uploadFiles } from "../telegram";
import { readFile } from "fs/promises";
import { asyncIteratorToArray } from "../utils/array";

export const FilesAPI: FastifyPluginCallback = async (fastify, _, done) => {
await fastify.register(multipart, {
Expand All @@ -18,7 +19,8 @@ export const FilesAPI: FastifyPluginCallback = async (fastify, _, done) => {
// This is to avoid working with req.files(), which is an async iterator... and a pain to work with.
// Files from saveRequestFiles() have a useless toBuffer method, so it needs to be replaced.
console.log("Saving file to disk...");
const files = (await req.saveRequestFiles()).map((file) => ({ ...file, toBuffer: () => readFile(file.filepath) }));
const files = await asyncIteratorToArray(req.files());
// const files = (await req.saveRequestFiles()).map((file) => ({ ...file, toBuffer: () => readFile(file.filepath) }));
console.log(`Start upload of ${files.length} files...`);
const ret = await uploadFiles(files);

Expand Down
8 changes: 8 additions & 0 deletions src/utils/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,11 @@ export function splitArrayIntoChunks<T>(arr: T[], chunkSize: number): T[][] {

return result;
}

export async function asyncIteratorToArray<T>(gen: AsyncIterable<T>): Promise<T[]> {
const out: T[] = [];
for await (const x of gen) {
out.push(x);
}
return out;
}

0 comments on commit 2b592a1

Please sign in to comment.