All files / utils downloadUtils.js

100% Statements 14/14
100% Branches 0/0
100% Functions 1/1
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                      10x 10x         6x 6x   6x 6x 6x 6x 6x 6x 6x   6x   4x 4x      
import axios from "axios";
import { toast } from "react-toastify";
 
/**
 * Download a CSV file from the backend and trigger a browser download.
 *
 * @param url the backend endpoint to GET
 * @param params query parameters, e.g. { courseId }
 * @param filename the name the downloaded file should get
 */
export async function downloadCsv({ url, params, filename }) {
  try {
    const response = await axios.get(url, {
      params,
      responseType: "blob",
    });
 
    const blob = new Blob([response.data], { type: "text/csv" });
    const objectUrl = window.URL.createObjectURL(blob);
 
    const link = document.createElement("a");
    link.href = objectUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(objectUrl);
 
    toast("Download successfully initiated.");
  } catch (error) {
    console.error("CSV download error:", error);
    toast.error("Failed to download the CSV. Please try again.");
  }
}