// MizQR Node.js example - Node.js 22+; no third-party dependencies. // You may copy and adapt this sample for your MizQR integrations. // Keep the API token on your server, never in browser code or a public repository. import { resolve } from "node:path"; import { fileURLToPath } from "node:url"; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const help = `MizQR API example (Node.js 22+) Set MIZQR_API_BASE to the API base shown in the MizQR API reference. Set MIZQR_API_TOKEN to a workspace API key in your server environment. Commands: node mizqr-api-example.mjs create --title "Menu campaign" --url https://example.com/menu node mizqr-api-example.mjs update QR_ID --url https://example.com/new-menu node mizqr-api-example.mjs analytics QR_ID --from 2026-11-01 --to 2026-11-14 QR_ID is the UUID returned in data.id, not the short-link code. Create adds a real dynamic QR record and consumes the applicable plan allowance. This sample does not export PNG/SVG artwork. Use the workspace to export the saved QR. Requests are never retried automatically; check the workspace after an uncertain write. `; export class MizqrApiError extends Error { constructor(status, validationFields = [], retryAfter = null) { const descriptions = { 401: "Check the API key.", 402: "Check the workspace plan and limits.", 403: "Check email verification, key scope and workspace permissions.", 404: "Check the returned QR ID and its workspace.", 422: "Correct the request fields.", 429: "Wait before making another request.", }; super(`MizQR API returned HTTP ${status}. ${descriptions[status] || "Check the API reference and service status."}`); this.name = "MizqrApiError"; this.status = status; this.validationFields = validationFields; this.retryAfter = retryAfter; } } export function createMizqrClient({ apiBase, token, fetchImpl = globalThis.fetch }) { let base; try { base = new URL(apiBase); } catch { throw new Error("Set MIZQR_API_BASE to the API base URL shown in the API reference."); } const local = ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname); if ((base.protocol !== "https:" && !(base.protocol === "http:" && local)) || base.username || base.password || base.search || base.hash) { throw new Error("Use an HTTPS API base without credentials, a query or a fragment. HTTP is supported only on localhost."); } if (typeof token !== "string" || !token || /\s/.test(token)) throw new Error("Set MIZQR_API_TOKEN to a valid workspace API key."); base.pathname = `${base.pathname.replace(/\/+$/, "")}/`; async function request(method, endpoint, body) { let response; try { response = await fetchImpl(new URL(endpoint, base), { method, redirect: "error", signal: AbortSignal.timeout(15_000), headers: { Accept: "application/json", Authorization: `Bearer ${token}`, ...(body ? { "Content-Type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}), }); } catch { throw new Error("Request did not complete. Check connectivity and the saved QR before retrying a create or update."); } let payload; try { payload = await response.json(); } catch { /* Do not log an HTML error page or response body. */ } if (!response.ok) { const fields = Object.keys(payload?.errors || {}).filter(key => /^[a-z0-9_.]+$/i.test(key)).slice(0, 20); const retry = response.headers.get("retry-after"); throw new MizqrApiError(response.status, fields, /^\d+$/.test(retry || "") ? Number(retry) : null); } if (!payload?.data || typeof payload.data !== "object" || Array.isArray(payload.data)) { throw new Error("Unexpected API response. Check the API base and the workspace before repeating a write."); } return payload.data; } function qrId(id) { if (typeof id !== "string" || !UUID.test(id)) throw new Error("Use the UUID from data.id as QR_ID."); return id; } function qrRecord(data) { if (!UUID.test(data.id || "") || typeof data.short_url !== "string") throw new Error("Unexpected QR response. Check the workspace before repeating a write."); return data; } return { async create({ title, destinationUrl }) { return qrRecord(await request("POST", "qrs", { title, type: "url", destination_url: destinationUrl })); }, async update(id, destinationUrl) { return qrRecord(await request("PATCH", `qrs/${qrId(id)}`, { destination_url: destinationUrl })); }, async analytics(id, { from, to } = {}) { const query = new URLSearchParams(); for (const [name, value] of Object.entries({ from, to })) { if (value === undefined) continue; const timestamp = Date.parse(`${value}T00:00:00Z`); if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(timestamp) || new Date(timestamp).toISOString().slice(0, 10) !== value) throw new Error("Use valid YYYY-MM-DD analytics dates."); query.set(name, value); } if (from && to && from > to) throw new Error("The start date must be before the end date."); const data = await request("GET", `qrs/${qrId(id)}/analytics${query.size ? `?${query}` : ""}`); if (typeof data.total_scans !== "number" || typeof data.unique_scans !== "number") throw new Error("Unexpected analytics response."); return data; }, }; } export async function runExample(args, env = process.env, fetchImpl = globalThis.fetch) { if (!args.length || args[0] === "--help") return help; const [command, ...rest] = args; const allowed = { create: ["--title", "--url"], update: ["--url"], analytics: ["--from", "--to"] }[command]; if (!allowed) throw new Error("Choose create, update or analytics. Use --help for examples."); const id = command === "create" ? undefined : rest.shift(); const options = {}; for (let i = 0; i < rest.length; i += 2) { const flag = rest[i], value = rest[i + 1]; if (!allowed.includes(flag) || !value || value.startsWith("--") || Object.hasOwn(options, flag)) throw new Error("Check the command flags. Use --help for examples."); options[flag] = value; } if (command === "create" && !options["--title"]?.trim()) throw new Error("Create requires --title."); if (command !== "analytics" && !options["--url"]) throw new Error("Create and update require --url."); const client = createMizqrClient({ apiBase: env.MIZQR_API_BASE, token: env.MIZQR_API_TOKEN, fetchImpl }); const data = command === "create" ? await client.create({ title: options["--title"], destinationUrl: options["--url"] }) : command === "update" ? await client.update(id, options["--url"]) : await client.analytics(id, { from: options["--from"], to: options["--to"] }); // Print only a small summary; tokens and full analytics responses are not logged. return command === "analytics" ? { total_scans: data.total_scans, unique_scans: data.unique_scans } : { id: data.id, short_url: data.short_url, destination_url: data.destination_url }; } if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { runExample(process.argv.slice(2)).then(result => process.stdout.write(typeof result === "string" ? result : `${JSON.stringify(result, null, 2)}\n`)).catch(error => { process.stderr.write(`${error.message}\n`); if (error instanceof MizqrApiError && error.validationFields.length) process.stderr.write(`Fields: ${error.validationFields.join(", ")}\n`); if (error instanceof MizqrApiError && error.retryAfter !== null) process.stderr.write(`Retry after: ${error.retryAfter} seconds.\n`); process.exitCode = 1; }); }