Skip to content

Instantly share code, notes, and snippets.

@agronom81
Created September 18, 2024 19:05
Show Gist options
  • Save agronom81/1a7c8f7eb3fe1181c34ea50bd5cf9313 to your computer and use it in GitHub Desktop.
Save agronom81/1a7c8f7eb3fe1181c34ea50bd5cf9313 to your computer and use it in GitHub Desktop.
save to file from database, node.js, knex.js, fastify
import { boomify } from '@hapi/boom';
import { Parser } from '@json2csv/plainjs';
import { Json2CSVBaseOptions } from '@json2csv/plainjs/dist/mjs/BaseParser';
import { FastifyReply } from 'fastify/types/reply';
import { Knex } from 'knex';
import { Transform } from 'stream';
export const writableStream = async (
opts: Omit<Json2CSVBaseOptions<object, object>, 'ndjson'> | undefined,
data: Knex.QueryBuilder<
{},
{
_base: {};
_hasSelection: false;
_keys: string;
_aliases: {};
_single: false;
_intersectProps: {};
_unionProps: never;
}[]
>,
reply: FastifyReply,
) => {
let isCSVHeaderSent = false;
const transform = new Transform({
writableObjectMode: true,
transform(chunk, encoding, callback) {
if (isCSVHeaderSent && opts) {
opts.header = false;
}
const parser = new Parser(opts);
isCSVHeaderSent = true;
this.push(parser.parse([chunk]) + '\n');
callback();
},
});
await data
.stream(function (stream) {
stream.pipe(transform);
})
.then(function () {
reply.header('Content-Type', 'text/csv');
return reply.send(transform);
})
.catch(function (e: any) {
throw boomify(e as Error);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment