From a410612dc61d87c70d3aef6eb7560a0c0d1dd5f0 Mon Sep 17 00:00:00 2001 From: benjaminjohnson2204 Date: Thu, 18 Apr 2024 15:42:05 -0700 Subject: [PATCH] Change VSR export function to send file directly to response instead of saving to disk (doesn't work on Vercel) --- backend/src/controllers/vsr.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/backend/src/controllers/vsr.ts b/backend/src/controllers/vsr.ts index 65e0f42..7634bad 100644 --- a/backend/src/controllers/vsr.ts +++ b/backend/src/controllers/vsr.ts @@ -1,6 +1,5 @@ -import { RequestHandler } from "express"; +import { RequestHandler, Response } from "express"; import { validationResult } from "express-validator"; -import fs from "fs"; import createHttpError from "http-errors"; import FurnitureItemModel, { FurnitureItem } from "src/models/furnitureItem"; import VSRModel, { FurnitureInput, VSR } from "src/models/vsr"; @@ -205,7 +204,7 @@ const stringifySelectedFurnitureItems = ( .join(", "); }; -const writeSpreadsheet = async (filename: string) => { +const writeSpreadsheet = async (filename: string, res: Response) => { const workbook = new ExcelJS.Workbook(); workbook.creator = "PAP Inventory System"; @@ -286,17 +285,19 @@ const writeSpreadsheet = async (filename: string) => { }); // Write to file - await workbook.xlsx.writeFile(filename); + await workbook.xlsx.write(res); }; export const bulkExportVSRS: RequestHandler = async (req, res, next) => { try { const filename = "vsrs.xlsx"; - await writeSpreadsheet(filename); - res.download(filename, () => { - // Once the flie has been sent to the requestor, remove it from our filesystem - fs.unlinkSync(filename); + // Set some headers on the response so the client knows that a file is attached + res.set({ + "Content-Disposition": `attachment; filename="${filename}"`, + "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }); + + await writeSpreadsheet(filename, res); } catch (error) { next(error); }