diff options
Diffstat (limited to 'pages/api/pdftron/createVendorDataReports.ts')
| -rw-r--r-- | pages/api/pdftron/createVendorDataReports.ts | 78 |
1 files changed, 60 insertions, 18 deletions
diff --git a/pages/api/pdftron/createVendorDataReports.ts b/pages/api/pdftron/createVendorDataReports.ts index 47f6055d..f461a7fb 100644 --- a/pages/api/pdftron/createVendorDataReports.ts +++ b/pages/api/pdftron/createVendorDataReports.ts @@ -1,5 +1,8 @@ import type { NextApiRequest, NextApiResponse } from "next"; +import type { File as FormidableFile } from "formidable"; import formidable from "formidable"; +import fs from "fs/promises"; +import { createReport } from "@/lib/pdftron/serverSDK/createReport"; export const config = { api: { @@ -15,22 +18,61 @@ export default async function handler( return res.status(405).end(); } - const form = formidable({ multiples: true }); - - form.parse(req, async (err, fields, files) => { - if (err) { - console.error(err); - return res.status(500).json({ error: "Error parsing form" }); - } - - try { - const additionalData = JSON.parse((fields?.additionalData ?? "") as string); - console.log("π¦ additionalData:", additionalData); - console.log("π files:", files.files); // files.filesλ array or single file - - return res.status(200).json({ success: true }); - } catch (e) { - return res.status(400).json({ error: "Invalid additionalData" }); - } - }); + try { + const form = formidable({ multiples: false }); + + form.parse(req, async (err, fields, files) => { + if (err) { + console.error(err); + return res.status(500).json({ error: "Error parsing form" }); + } + + try { + const fileName = fields?.customFileName?.[0] ?? ""; + const reportDatas = JSON.parse(fields?.reportDatas?.[0] ?? "[]") as { + [key: string]: any; + }[]; + const reportTempPath = fields?.reportTempPath?.[0] ?? ""; + const reportCoverPage: FormidableFile | undefined = files?.file?.[0]; + + if ( + !reportCoverPage || + fileName.length === 0 || + reportDatas.length === 0 || + reportTempPath.length === 0 + ) { + return res.status(400).json({ error: "Invalid Report Data" }); + } + + const buffer = await fs.readFile(reportCoverPage.filepath); + + const { + result, + buffer: pdfBuffer, + error, + } = await createReport(buffer, reportTempPath, reportDatas); + + if (result && pdfBuffer) { + res.setHeader("Content-Type", "application/pdf"); + res.setHeader( + "Content-Disposition", + `attachment; filename="${fileName}"` + ); + + return res.send(Buffer.from(pdfBuffer)); + } + + return res.status(200).json({ + success: false, + message: "Report μμ±μ μ€ν¨νμμ΅λλ€.", + error, + }); + } catch (e) { + console.log(e); + return res.status(400).json({ error: "Invalid additionalData" }); + } + }); + } catch (err) { + return res.status(401).end(); + } } |
