Full blown example.
This commit is contained in:
44
src/pages/api/v1/rom.ts
Normal file
44
src/pages/api/v1/rom.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
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;
|
||||
Reference in New Issue
Block a user