Skip to content

Commit

Permalink
Download CSV data as stream
Browse files Browse the repository at this point in the history
  • Loading branch information
peterpolman committed Jul 2, 2024
1 parent 1675250 commit ba5ab15
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,37 @@ const controller = async (req: Request, res: Response) => {
// Export all participant data
const data = await ParticipantService.export(pool);

// Write CSV file
const csv = await CSVService.stringify(data);

// Prepare the response headers for file download
const fileName = `participants${pool.id}.csv`;
res.setHeader('Content-Disposition', `attachment; filename=${fileName}`);
res.setHeader('Content-Type', 'text/csv');

// Stream the CSV data to the client
res.send(csv);
// Define columns for CSV
const columns = Object.keys(data[0]);

// Write the CSV header
const csvHeader = CSVService.stringify([], { columns, header: true });
res.write(csvHeader);

// Write each row
for (const row of data) {
const csvRow = CSVService.stringify([
[
row.accountId,
row.twitterId,
row.discordId,
row.googleId,
row.username,
row.email,
row.wallets,
row.createdAt,
],
]);
res.write(csvRow);
}

// End the response
res.end();
};

export { controller, validation };
7 changes: 3 additions & 4 deletions apps/api/src/app/services/CSVService.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { stringify } from 'csv-stringify/sync';
import { stringify, Options } from 'csv-stringify/sync';

export default class CSVService {
static async stringify(data: any[]) {
const columns = Object.keys(data[0]);
return stringify(data, { columns, header: true });
static stringify(data: any[], options?: Options) {
return stringify(data, options);
}
}

0 comments on commit ba5ab15

Please sign in to comment.