Exam generation rework, batch user tables, fastapi endpoint switch
This commit is contained in:
79
src/pages/api/exam/[module]/import.ts
Normal file
79
src/pages/api/exam/[module]/import.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
export const config = {
|
||||
api: {
|
||||
bodyParser: false
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import axios from "axios";
|
||||
import formidable from 'formidable';
|
||||
import FormData from 'form-data';
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") return post(req, res);
|
||||
|
||||
return res.status(404).json({ ok: false });
|
||||
}
|
||||
|
||||
|
||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.session.user) return res.status(401).json({ ok: false });
|
||||
|
||||
try {
|
||||
const form = formidable({
|
||||
multiples: true,
|
||||
});
|
||||
|
||||
const [_, files] = await form.parse(req);
|
||||
const formData = new FormData();
|
||||
|
||||
if (files.exercises?.[0]) {
|
||||
const file = files.exercises[0];
|
||||
const buffer = readFileSync(file.filepath);
|
||||
|
||||
formData.append('exercises', buffer, {
|
||||
filename: file.originalFilename!,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
knownLength: buffer.length
|
||||
});
|
||||
}
|
||||
|
||||
if (files.solutions?.[0]) {
|
||||
const file = files.solutions[0];
|
||||
const buffer = readFileSync(file.filepath);
|
||||
|
||||
formData.append('solutions', buffer, {
|
||||
filename: file.originalFilename!,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
knownLength: buffer.length
|
||||
});
|
||||
}
|
||||
|
||||
const result = await axios.post(
|
||||
`${process.env.BACKEND_URL}/${req.query.module}/import`,
|
||||
formData,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
|
||||
...formData.getHeaders()
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).json(result.data);
|
||||
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return res.status(500).json({
|
||||
error: 'Upload failed',
|
||||
details: error instanceof Error ? error.message : 'Unknown error'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user