2025-03-11 13:58:20 -05:00

44 lines
1.0 KiB
TypeScript

import { NextApiHandler } from "next";
import * as fs from 'fs';
import * as path from 'path';
const PATH_ROMS = path.resolve('.', 'data', 'games');
const handler:NextApiHandler = async (req, res) => {
if (req.method !== 'GET') {
res.setHeader('Allow', ['GET']);
res.status(405).end(`Method Not Allowed`);
return;
}
// ID query param
if(!req.query.id || typeof req.query.id !== 'string') {
res.status(404).end(`Not Found`);
return;
}
const { id } = req.query;
if(!id) {
res.status(404).end(`Not Found`);
return;
}
// Does rom exist?
const pathRom = path.resolve(PATH_ROMS, `${id}.bin`);
if(!fs.existsSync(pathRom)) {
res.status(404).end(`Not Found`);
return;
}
// Read rom
try {
const romStream = fs.createReadStream(pathRom);
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', `attachment; filename="${id}.bin"`);
romStream.pipe(res);
} catch (error) {
res.status(500).end(`Internal Server Error`);
}
};
export default handler;