Sadum1's picture
Upload pdfs.ts
7219e07 verified
Raw History Blame Contribute Delete
2.67 kB
/**
* PDF linking API client.
*
* File : frontend/src/api/pdfs.ts (new)
* Purpose : call the routes in backend/app/pdf_routes.py.
* Consumers: PdfLibraryPanel.
* The paper id travels as a query parameter (ids can contain slashes).
*/
const BASE = "/api/v1/protocols";
export interface PdfInfo {
paper_id: string;
filename: string;
size_bytes: number;
sha256: string;
uploaded_at: string;
uploaded_by: string | null;
}
export interface StudyPdfRow {
paper_id: string;
title: string;
authors: string;
year: string | null;
doi: string | null;
url: string | null;
pdf: PdfInfo | null;
}
export const MAX_PDF_BYTES = 25 * 1024 * 1024;
export class PdfApiError extends Error {}
async function fail(res: Response): Promise<never> {
let detail = `Request failed (${res.status}).`;
try {
const body = (await res.json()) as { detail?: unknown };
if (typeof body.detail === "string") detail = body.detail;
} catch {
/* keep the default message */
}
throw new PdfApiError(detail);
}
async function send(url: string, init?: RequestInit): Promise<Response> {
try {
return await fetch(url, init);
} catch {
throw new PdfApiError("Could not reach the server. Check your connection and try again.");
}
}
const q = (paperId: string) => `paper_id=${encodeURIComponent(paperId)}`;
export function pdfUrl(protocolId: string, paperId: string): string {
return `${BASE}/${encodeURIComponent(protocolId)}/pdf?${q(paperId)}`;
}
export async function listStudyPdfs(protocolId: string): Promise<StudyPdfRow[]> {
const res = await send(`${BASE}/${encodeURIComponent(protocolId)}/pdfs`);
if (!res.ok) return fail(res);
return (await res.json()) as StudyPdfRow[];
}
export async function attachPdf(
protocolId: string,
paperId: string,
file: File,
uploadedBy: string,
replace: boolean,
): Promise<PdfInfo> {
if (file.size > MAX_PDF_BYTES) {
throw new PdfApiError("This file is larger than 25 MB, so it cannot be attached.");
}
const res = await send(
`${BASE}/${encodeURIComponent(protocolId)}/pdf?${q(paperId)}&replace=${replace}`,
{
method: "POST",
headers: {
"Content-Type": "application/pdf",
"X-Filename": encodeURIComponent(file.name),
"X-Uploaded-By": encodeURIComponent(uploadedBy),
},
body: file,
},
);
if (!res.ok) return fail(res);
return (await res.json()) as PdfInfo;
}
export async function removePdf(protocolId: string, paperId: string): Promise<void> {
const res = await send(`${BASE}/${encodeURIComponent(protocolId)}/pdf?${q(paperId)}`, {
method: "DELETE",
});
if (!res.ok) return fail(res);
}