import express from "express";
import multer from "multer";
const app = express();
const upload = multer({ limits: { fileSize: 12 * 1024 * 1024 } });
const API_URL = process.env.FLASH_MD_API_URL || "https://api.markpdf.tech";
const API_KEY = process.env.FLASH_MD_API_KEY;
async function pollJob(jobId) {
while (true) {
await new Promise((r) => setTimeout(r, 5000));
const res = await fetch(`${API_URL}/jobs/${jobId}`, {
headers: { "x-api-key": API_KEY },
});
const data = await res.json();
if (data.status === "completed") return data.body;
if (data.status === "failed") throw new Error(data.error);
}
}
app.post("/convert", upload.single("file"), async (req, res) => {
if (!req.file) return res.status(400).json({ error: "Missing file" });
const upstream = await fetch(
`${API_URL}/convert/raw?filename=${encodeURIComponent(req.file.originalname)}&mode=fast`,
{
method: "POST",
headers: {
"x-api-key": API_KEY,
"content-type": req.file.mimetype,
},
body: req.file.buffer,
}
);
if (upstream.status === 200) {
return res.type("text/markdown").send(await upstream.text());
}
if (upstream.status === 202) {
const job = await upstream.json();
const markdown = await pollJob(job.job_id);
return res.type("text/markdown").send(markdown);
}
res.status(upstream.status).send(await upstream.text());
});
app.listen(3000);