Keskas Aymen
Keskas Aymen
HHono
Created by Keskas Aymen on 9/13/2024 in #help
Returning multiple files as a stream
i want to return multiple files by archiving them but for some reason the resulted archive is corrupted
ts

export const readAllHandler: RouteHandler<
typeof readAllRoute,
AuthorizationBinding
> = async (c) => {
const { tags } = c.req.valid('query');
const storeId = c.get('storeId');

const matchedFiles = (
await db.query.fileTable.findMany({
where: and(
eq(fileTable.storeId, storeId),
arrayContains(fileTable.tags, tags),
),
})
).map((entry) => Bun.file(getFilePath(entry)));

if (matchedFiles.length === 0) return c.notFound();

const res = honoStream(c, async (stream) => {
const tar = archiver('tar');

tar.on('data', (chunk) => {
stream.write(chunk);
});

tar.on('end', () => {
stream.close();
});

for (let file of matchedFiles) {
if (!(await file.exists())) continue;
await file.stream().pipeTo(
new WritableStream({
write(chunk) {
tar.write(chunk);
},
}),
);
}

tar.end();
});

res.headers.append('Content-Type', 'application/x-tar');
res.headers.append('Content-Disposition', 'attachment; filename="files.tar"');
return res;
};
ts

export const readAllHandler: RouteHandler<
typeof readAllRoute,
AuthorizationBinding
> = async (c) => {
const { tags } = c.req.valid('query');
const storeId = c.get('storeId');

const matchedFiles = (
await db.query.fileTable.findMany({
where: and(
eq(fileTable.storeId, storeId),
arrayContains(fileTable.tags, tags),
),
})
).map((entry) => Bun.file(getFilePath(entry)));

if (matchedFiles.length === 0) return c.notFound();

const res = honoStream(c, async (stream) => {
const tar = archiver('tar');

tar.on('data', (chunk) => {
stream.write(chunk);
});

tar.on('end', () => {
stream.close();
});

for (let file of matchedFiles) {
if (!(await file.exists())) continue;
await file.stream().pipeTo(
new WritableStream({
write(chunk) {
tar.write(chunk);
},
}),
);
}

tar.end();
});

res.headers.append('Content-Type', 'application/x-tar');
res.headers.append('Content-Disposition', 'attachment; filename="files.tar"');
return res;
};
1 replies
HHono
Created by Keskas Aymen on 9/11/2024 in #help
zod-openapi infering route handler type from route handler
No description
6 replies