Using tRPC for uploading audio files

I want to create an api router in tRPC but am not sure if the following code is doable with tRPC. If yes can you point me to a resource where I can learn how to do it?
import FormData from "form-data";
import { withFileUpload } from "next-multiparty";
import { createReadStream } from "fs";
import { type NextRequest, type NextResponse } from "next/server";

export const config = {
api: {
bodyParser: false,
},
};

const handler = withFileUpload(async (req: NextRequest, res: NextResponse) => {
const file = req.file;
if (!file) {
res.status(400).send("No file uploaded");
return;
}
// Create form data
const formData = new FormData();
formData.append("file", createReadStream(file.filepath), "audio.wav");
formData.append("model", "whisper-1");
const response = await fetch(
"https://api.openai.com/v1/audio/transcriptions",
{
method: "POST",
headers: {
...formData.getHeaders(),
Authorization: `...`,
},
body: formData,
}
);
const { text, error } = await response.json();

if (response.ok) {
res.status(200).json({ text: text });
} else {
console.log("OPEN AI ERROR:");
console.log(error.message);
res.status(400).send(new Error());
}
});

export default handler;
import FormData from "form-data";
import { withFileUpload } from "next-multiparty";
import { createReadStream } from "fs";
import { type NextRequest, type NextResponse } from "next/server";

export const config = {
api: {
bodyParser: false,
},
};

const handler = withFileUpload(async (req: NextRequest, res: NextResponse) => {
const file = req.file;
if (!file) {
res.status(400).send("No file uploaded");
return;
}
// Create form data
const formData = new FormData();
formData.append("file", createReadStream(file.filepath), "audio.wav");
formData.append("model", "whisper-1");
const response = await fetch(
"https://api.openai.com/v1/audio/transcriptions",
{
method: "POST",
headers: {
...formData.getHeaders(),
Authorization: `...`,
},
body: formData,
}
);
const { text, error } = await response.json();

if (response.ok) {
res.status(200).json({ text: text });
} else {
console.log("OPEN AI ERROR:");
console.log(error.message);
res.status(400).send(new Error());
}
});

export default handler;
N
Nick418d ago
You can’t post files directly to a procedure in tRPC (yet) so it’s best to use a file host like S3 and generate an upload uri for the client to use
M
mozzius418d ago
Either that or convert to base64 (worse option but technically possible)