Files
formbricks/apps/web/app/api/internal/csv-conversion/route.ts
T
Jonas Höbenreich 89a60fd568 feat: add Excel download option (#846)
* add Excel download option

* add back attribute export

* add types and check for download filetype

* add xlsx package

* move csv and excel conversion to internal endpoints

---------

Co-authored-by: Matthias Nannt <mail@matthiasnannt.com>
2023-10-02 17:04:11 +02:00

43 lines
1.0 KiB
TypeScript
Executable File

import { NextRequest, NextResponse } from "next/server";
import { AsyncParser } from "@json2csv/node";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { responses } from "@/lib/api/response";
export async function POST(request: NextRequest) {
const session = await getServerSession(authOptions);
if (!session) {
return responses.unauthorizedResponse();
}
const data = await request.json();
let csv: string = "";
const { json, fields, fileName } = data;
const parser = new AsyncParser({
fields,
});
try {
csv = await parser.parse(json).promise();
} catch (err) {
console.log({ err });
throw new Error("Failed to convert to CSV");
}
const headers = new Headers();
headers.set("Content-Type", "text/csv;charset=utf-8;");
headers.set("Content-Disposition", `attachment; filename=${fileName ?? "converted"}.csv`);
return NextResponse.json(
{
fileResponse: csv,
},
{
headers,
}
);
}