JavaScript (Node.js)
Un script de Node.js que usa la API con el fetch integrado en Node 18 y posteriores: no hay que instalar paquetes. Enumera las variables etiquetadas de una plantilla, mide el dibujo que genera con los valores dados y lo exporta como PDF.
Descárguelo: box.mjs.
// box.mjs: list a template's inputs, measure it and export it as a PDF with the PiQ SaaS API.
// Node 18 or later; no packages needed.
import { writeFile } from "node:fs/promises";
const key = process.env.PIQ_API_KEY;
const base = (process.env.PIQ_URL ?? "https://saas.parametriq.co.uk").replace(/\/$/, "");
const storage = process.env.PIQ_STORAGE; // optional: a registered storage's name
if (!key) {
console.error("Set PIQ_API_KEY to your API key.");
process.exit(1);
}
const TEMPLATE =
'L=400,"Length"\nW=300,"Width"\nP1=[L,0]\nP2=[L,W]\nP3=[0,W]\nPOLYLINE @1,[P0,P1,P2,P3],TRUE,0';
// the template itself, or (optional) where it is kept in your storage
const template = storage
? { source: { storage, key: "templates/box.piq" } }
: { template: TEMPLATE };
const values = { L: 500, W: 250 };
async function post(path, body) {
const response = await fetch(base + path, {
method: "POST",
headers: { "X-API-KEY": key, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!response.ok) await fail(response);
return response;
}
async function fail(response) {
console.error(`Error ${response.status} ${response.statusText}`);
const text = await response.text(); // a 401 has no body
if (text) {
let problem = {};
try { problem = JSON.parse(text); } catch { console.error(text); }
if (problem.title) console.error(problem.title);
if (problem.detail) console.error(problem.detail);
for (const [field, messages] of Object.entries(problem.errors ?? {}))
console.error(` ${field}: ${messages.join(" ")}`);
}
process.exit(1);
}
// 1. The template's labelled variables
const { inputs } = await (await post("/inputs", template)).json();
for (const input of inputs)
console.log(`${input.name}: ${input.label} (${input.kind}, ${input.value})`);
// 2. The drawing measured, with the values given
const m = await (await post("/measure", { ...template, values })).json();
const cut = m.layers.find((layer) => layer.layer === "Cut")?.length ?? 0;
console.log(`Size: ${m.width} x ${m.height}, cut length: ${cut}`);
// 3. The drawing as a PDF
const pdf = await post("/export/pdf", { ...template, values });
await writeFile("box.pdf", Buffer.from(await pdf.arrayBuffer()));
console.log(`Saved box.pdf (${pdf.headers.get("X-PiQ-Warnings")} warnings)`);
// 4. Optional: the PDF saved to your storage instead of downloaded
if (storage) {
const destination = { storage, key: "drawings/box.pdf" };
const body = { ...template, values, destination, overwrite: true };
const saved = await (await post("/save/pdf", body)).json();
console.log(`Saved ${saved.key} to ${saved.storage} (${saved.size} bytes)`);
}
Cómo funciona
- Configuración. La clave se toma de
PIQ_API_KEY, la dirección dePIQ_URL(el propio servicio si no está definida) y, opcionalmente, el nombre de un almacenamiento dePIQ_STORAGE. Sin clave, el script se detiene de inmediato. - La plantilla.
templatees el cuerpo del que parte cada solicitud: el texto de la plantilla comotemplateo, cuandoPIQ_STORAGEestá definida, dónde está guardada en su almacenamiento comosource.valuesdaLyWpor nombre. postenvía un cuerpo a una operación como JSON, con la clave en el encabezadoX-API-KEY. Una respuesta que no es correcta (response.okes false) pasa afail; cualquier otra se devuelve para leerla.failimprime el estado y después la descripción del problema: sutitle, sudetaily cada entrada deerrors, el campo y qué está mal en él. Un401no tiene cuerpo, así que primero se lee el cuerpo como texto y solo se analiza cuando lo hay; un cuerpo que no es JSON se imprime tal cual. Después, el script termina con1.- Inputs.
POST /inputssolo necesita la plantilla. Cada uno de susinputstiene unname,label,kindyvalue. - Measure.
POST /measurecon los valores da elwidthy elheightdel dibujo, y las longitudes de sus líneas por capa enlayers; la longitud de corte es la longitud en la capaCut. - Export.
POST /export/pdfresponde con el propio PDF, no con JSON: se lee conarrayBuffer()y se escribe enbox.pdf. El encabezadoX-PiQ-Warningsindica cuántas cosas no pudieron exportarse tal cual. - Save (opcional). Con un almacenamiento,
POST /save/pdfexporta el mismo dibujo y lo guarda en su almacenamiento endestination;overwrite: truereemplaza un archivo que ya exista. Responde con dónde lo ha guardado y su tamaño.
Cómo ejecutarlo
Guarde el script como box.mjs (la extensión .mjs le permite usar import y await en el nivel superior) y, a
continuación:
export PIQ_API_KEY=XXXX-XXXX-XXXX-XXXXX
node box.mjs
Imprime las variables etiquetadas de la plantilla, el tamaño del dibujo y su longitud de corte, y guarda box.pdf:
L: Length (Number, 400)
W: Width (Number, 300)
D: Depth (Number, 300)
Size: 500 x 250, cut length: 1500
Saved box.pdf (0 warnings)
Con un valor que la plantilla no puede usar (por ejemplo, "L": "long"), imprime el problema y se detiene:
Error 400 Bad Request
One or more validation errors occurred.
Some of the values given can't be used.
L: L is a number.
Con una clave incorrecta, solo imprime Error 401 Unauthorized: un 401 no tiene
descripción del problema.
Para probar la parte del almacenamiento, registre un almacenamiento (consulte
Registrar un almacenamiento), coloque en él una plantilla como templates/box.piq y
establezca PIQ_STORAGE con el nombre del almacenamiento. La plantilla se lee entonces desde su almacenamiento, y el
PDF también se guarda en él como drawings/box.pdf, reemplazando cualquier archivo que ya exista.
Consulte también: API, Inputs, Measure, Exportar un dibujo, Guardar en su almacenamiento, Registrar un almacenamiento, Clientes.