49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
|
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 {getStorage, ref, uploadBytes} from "firebase/storage";
|
|
import fs from "fs";
|
|
import {app} from "@/firebase";
|
|
|
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
|
|
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
if (!req.session.user) {
|
|
res.status(401).json({ok: false});
|
|
return;
|
|
}
|
|
|
|
const storage = getStorage(app);
|
|
|
|
const form = formidable({keepExtensions: true});
|
|
await form.parse(req, async (err: any, fields: any, files: any) => {
|
|
const audioFile = files.audio;
|
|
const audioFileRef = ref(storage, `speaking_recordings/${(audioFile as any).path.replace("upload_", "")}`);
|
|
|
|
const binary = fs.readFileSync((audioFile as any).path).buffer;
|
|
const snapshot = await uploadBytes(audioFileRef, binary);
|
|
|
|
const backendRequest = await axios.post(
|
|
`${process.env.BACKEND_URL}/speaking_task_1`,
|
|
{question: fields.question, answer: snapshot.metadata.fullPath},
|
|
{
|
|
headers: {
|
|
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
|
|
},
|
|
},
|
|
);
|
|
|
|
fs.rmSync((audioFile as any).path);
|
|
res.status(200).json({...backendRequest.data, fullPath: snapshot.metadata.fullPath});
|
|
});
|
|
}
|
|
|
|
export const config = {
|
|
api: {
|
|
bodyParser: false,
|
|
},
|
|
};
|