Initial SeConectai briefing system
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { getBriefingPerguntaParaUpload } from "@/lib/anexo-service";
|
||||
import { assertSameOrigin, rateLimitResponse } from "@/lib/request-security";
|
||||
import { removeStoredFile, validateAndStoreUpload } from "@/lib/storage";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
{
|
||||
params
|
||||
}: {
|
||||
params: { briefingId: string; perguntaId: string };
|
||||
}
|
||||
) {
|
||||
const originError = assertSameOrigin(request);
|
||||
if (originError) return originError;
|
||||
|
||||
const rateLimitError = rateLimitResponse(`upload:${params.briefingId}:${params.perguntaId}`, 30, 60 * 60 * 1000);
|
||||
if (rateLimitError) return rateLimitError;
|
||||
|
||||
const { briefing } = await getBriefingPerguntaParaUpload(params.briefingId, params.perguntaId);
|
||||
|
||||
if (briefing.status !== "RASCUNHO") {
|
||||
return NextResponse.json(
|
||||
{ message: "Briefing enviado nao aceita novos anexos." },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
const count = await db.anexo.count({
|
||||
where: {
|
||||
briefingId: params.briefingId,
|
||||
perguntaId: params.perguntaId
|
||||
}
|
||||
});
|
||||
|
||||
if (count >= 20) {
|
||||
return NextResponse.json(
|
||||
{ message: "Limite de 20 arquivos por pergunta atingido." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const formData = await request.formData();
|
||||
const file = formData.get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
return NextResponse.json({ message: "Arquivo nao enviado." }, { status: 400 });
|
||||
}
|
||||
|
||||
let storedFile: Awaited<ReturnType<typeof validateAndStoreUpload>> | null = null;
|
||||
|
||||
try {
|
||||
storedFile = await validateAndStoreUpload(file);
|
||||
|
||||
const anexo = await db.anexo.create({
|
||||
data: {
|
||||
briefingId: params.briefingId,
|
||||
perguntaId: params.perguntaId,
|
||||
nomeOriginal: storedFile.originalName,
|
||||
caminho: storedFile.storedPath,
|
||||
mime: storedFile.mime,
|
||||
tamanho: storedFile.size
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
nomeOriginal: true,
|
||||
mime: true,
|
||||
tamanho: true
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json({ anexo });
|
||||
} catch (error) {
|
||||
if (storedFile) {
|
||||
await removeStoredFile(storedFile.storedPath);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ message: error instanceof Error ? error.message : "Nao foi possivel enviar o arquivo." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user