import fs from "node:fs"; import path from "node:path"; import { parse } from "csv-parse/sync"; import { readFile } from "node:fs/promises"; import { getApiKey } from "../zygonApi"; const API_ENDPOINT = process.env.API_ENDPOINT ?? "https://api.zygon.tech"; type Email = { subject?: string; sender?: string; to?: string; timestamp?: string; }; export const commandUploadEmails = async (csvPath: string) => { if (!fs.existsSync(csvPath)) { console.error("No folder nor file found at", path.resolve(csvPath)); process.exit(1); } const apiKey = getApiKey(); const files: Array = []; if (fs.lstatSync(csvPath).isDirectory()) { files.push( ...(await fs.promises.readdir(csvPath, { recursive: true })).map((c) => path.resolve(csvPath, c), ), ); } else { files.push(path.resolve(csvPath)); } for (const file of files) { console.log(`Uploading ${file}...`); await uploadFile(apiKey, file); } }; async function uploadFile(apiKey: string, csvPath: string) { const emailsBuffer = await readFile(csvPath); const emails: Array = parse(emailsBuffer, { delimiter: ",", columns: true, skip_empty_lines: true, }); console.log(` ${emails.length} email${emails.length > 1 ? "s" : ""} found`); try { const response = await fetch(`${API_ENDPOINT}/upload-emails`, { method: "POST", headers: { authorization: `Bearer ` + getApiKey(), "Content-Type": "application/json", }, body: JSON.stringify({ emails, }), }); const result = await response.json(); if (response.status >= 400) { console.error(" ✘ The emails failed to be processed"); console.error(` ${(result as { message: string }).message}`); } else { Object.entries( (result as { stats: Record }).stats, ).forEach(([description, stat]) => console.log(` ${description}: ${stat}`), ); console.log(" ✓ Emails sent successfuly"); } } catch (e) { console.error( `We couldn't reach the Zygon server for the following reason:`, (e as { message: string }).message, ); process.exit(3); } }