JSON definition · shared/definitions/relational-storage.v1.jsonView on GitHub
{
"title": "Insurance claim",
"elements": [
{
"type": "text",
"name": "q_email",
"valueName": "customer_email",
"dbColumn": "claims.customer_email",
"title": "Email",
"inputType": "email",
"isRequired": true
},
{
"type": "text",
"name": "q_amount",
"valueName": "amount",
"dbColumn": "claims.amount",
"title": "Amount claimed",
"inputType": "number",
"min": 0
},
{
"type": "dropdown",
"name": "incident",
"title": "What happened?",
"choices": [
{
"value": "collision",
"text": "Collision"
},
{
"value": "theft",
"text": "Theft"
},
{
"value": "weather",
"text": "Storm or flood"
}
]
},
{
"type": "comment",
"name": "details",
"title": "Details"
},
{
"type": "boolean",
"name": "priority_handling",
"title": "Priority handling"
}
]
}
Client · src/app/examples/server-pdf/client.tsx · sjs:server-pdf.clientView on GitHub
// Open a tab during the click and navigate only after the server returns a PDF
async function generatePdf(id: string, action: PdfAction): Promise<PdfResult> {
if (urls.has(id)) return deliverPdf(id, action, urls.get(id)!);
const tab = action === "open" ? window.open("/examples/server-pdf/loading", "_blank") : null;
try {
const response = await fetch(`/api/claims/${id}/pdf`);
if (!response.ok) throw await responseError(response, "Couldn't generate the PDF. Please try again.");
if (!response.headers.get("content-type")?.startsWith("application/pdf")) throw new Error("The server didn't return a PDF. Please try again.");
const blob = await response.blob();
if (!blob.size) throw new Error("The server returned an empty PDF. Please try again.");
const url = URL.createObjectURL(blob);
urls.set(id, url);
if (action === "download") return deliverPdf(id, action, url);
const opened = tab && !tab.closed;
if (opened) tab.location = url;
return { message: opened ? "PDF opened in a new tab." : "PDF ready. Select Open PDF again or Download PDF.", needsAction: !opened };
} catch (error) { tab?.close(); throw error; }
}
Server · src/server/routes/server-pdf.ts · sjs:server-pdf.serverView on GitHub
// GET /api/claims/:id/pdf — fill the claim's definition with its answers and send the PDF
export async function claimPdf(req: Request, { id }: { id: string }) {
const claim = (/^\d+$/.test(id)
? db(req).prepare("SELECT data, definition_version FROM responses WHERE form_id = 'claim' AND id = ?").get(id)
: undefined) as { data: string; definition_version: string | null } | undefined;
if (!claim) throw httpError(404, "Unknown claim");
const version = claim.definition_version; // use the schema version recorded with the response
const json = version === "v1" || version === "v2" ? versioned(version)
: version === null ? (db(req).prepare("SELECT json FROM forms WHERE key = 'claim'").get() as { json: string } | undefined)?.json : undefined;
if (json === undefined) throw httpError(409, "The schema version for this claim is unavailable");
const definition = JSON.parse(json);
if (lintSurvey(definition, lintOptions).findings.some((finding) => finding.severity === "error")) {
surveyjs.logFailure("server-pdf", `the definition of claim ${id} has errors`);
return Response.json({ error: "The stored definition has errors" }, { status: 500 });
}
const pdf = await surveyjs.renderPdf(definition, JSON.parse(claim.data)).catch((error: unknown) => error); // new SurveyPDF(…)
if (!surveyjs.isPdf(pdf)) { // it threw, or its bytes aren't a PDF
surveyjs.logFailure("server-pdf", pdf);
return Response.json({ error: "Couldn't generate the PDF" }, { status: 500 });
}
return new Response(new Uint8Array(pdf), { headers: {
"Content-Type": "application/pdf", "Content-Disposition": `inline; filename="claim-${id}.pdf"`, "Cache-Control": "private, no-store",
} });
}