Skip to content
中文

Build a product catalogue

Build a product catalogue across Media, File, Database and Knowledge: public images, private source documents, structured current references and searchable specifications. This disposable example creates one kettle, updates its capacity from 1.5 to 1.8 liters, verifies the new revision, then cleans up.

Prerequisites

Use Node.js 22 or Bun with an API key that can create Media, File, Database and Knowledge resources. Save the code as catalogue.mjs. Set PRAXIS_API_KEY to your key, then run node catalogue.mjs. The default base is https://api.deepraxis.com. Keep keys on the server.

Identity and metadata

ProductIdentity and business projectionAccess
DatabaseSKU is the unique business key; row id identifies the record. Typed columns save library, asset, File and store IDs plus current revision.Authenticated; publication_state is an ordinary column, not access control.
MediaLibrary ID scopes asset IDs; public_id names delivery. tags and string context project SKU/revision.Delivery is public. Importing a private File creates an independent public copy, not a protected reference.
FileFile ID identifies immutable bytes; filename is a label. purpose=user_data is a storage purpose, not business metadata.Native content download needs authentication; compatible APIs reject user-upload downloads.
KnowledgeStore ID scopes an attachment whose ID is the source File ID. Typed attributes carry SKU and numeric revision.Authenticated search; store metadata is a string map.

Treat returned IDs as opaque. Database string references do not enforce cross-product foreign keys. A Knowledge detach does not delete its source File; File deletion/expiry revokes its Knowledge attachment. It does not remove an independent Media copy.

Create, index and switch references

The single script below uploads text specifications so no PDF tooling is required. The synthetic image tests wiring, not image-recognition quality. Each revision gets a new Media public_id: overwrite would make the old version URL unavailable at the service. Metadata maps are complete replacements, so send all keys you intend to retain.

const imageDataUri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAIAAABMXPacAAABWklEQVR4nO3OQQ0AMBAEofVv+iqDxzRBALvtg/wgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwgzg/i/CDOD+L8IM4P4vwg7gEgaMOyrMtNTwAAAABJRU5ErkJggg==";
const base = process.env.PRAXIS_API_BASE ?? "https://api.deepraxis.com";
const key = process.env.PRAXIS_API_KEY;
if (!key) throw new Error("Set PRAXIS_API_KEY");
const sku = "KETTLE-RED";
async function api(path, method = "GET", body, extra = {}) {
const form = body instanceof FormData;
const response = await fetch(base + path, {
method, headers: { Authorization: `Bearer ${key}`,
...(!form && body !== undefined ? { "Content-Type": "application/json" } : {}), ...extra },
body: body === undefined ? undefined : form ? body : JSON.stringify(body),
signal: AbortSignal.timeout(120000),
});
const text = await response.text();
if (!response.ok) throw new Error(`${method} ${path}: ${response.status} ${text}`);
return text ? JSON.parse(text) : null;
}
const created = { files: [], attachments: [] };
let library, database, store;
const name = `catalogue-${Date.now()}`;
try {
library = await api("/media/v1/libraries", "POST", { name, labels: { merchant: "demo" } });
database = await api("/database/v1/table", "POST", { name, labels: { merchant: "demo" } });
store = await api("/knowledge/v1/vector_stores", "POST", { name, metadata: { merchant: "demo" } });
const db = `/database/v1/table/${database.id}`;
const media = `/media/v1/libraries/${library.id}`;
const knowledge = `/knowledge/v1/vector_stores/${store.id}`;
await api(`${db}/tables`, "POST", { name: "products", fields: [
{ name: "sku", type: "string", required: true, unique: true },
...["media_library_id", "image_asset_id", "spec_file_id", "knowledge_store_id", "publication_state"].map(name => ({ name, type: "string" })),
{ name: "revision", type: "integer" },
] });
async function prepare(revision, capacity) {
const text = `SKU: ${sku}. Revision ${revision}. Red kettle capacity: ${capacity} liters.`;
const form = new FormData();
form.set("purpose", "user_data");
form.set("file", new Blob([text], { type: "text/plain" }), `kettle-r${revision}.txt`);
const file = await api("/file/v1/files", "POST", form);
created.files.push(file.id);
await api(`${knowledge}/files`, "POST", { file_id: file.id, attributes: { sku, revision, merchant: "demo" } });
created.attachments.push(file.id);
const deadline = Date.now() + 30 * 60 * 1000;
for (;;) {
const indexed = await api(`${knowledge}/files/${file.id}`);
if (indexed.status === "completed") break;
if (["failed", "cancelled"].includes(indexed.status)) throw new Error(JSON.stringify(indexed.last_error));
if (Date.now() >= deadline) throw new Error(`Index deadline: ${file.id}`);
await new Promise(resolve => setTimeout(resolve, 2000));
}
// A new delivery identity preserves the old image while readers still use it.
const asset = await api(`${media}/assets`, "POST", {
file: imageDataUri, type: "upload", public_id: `catalogue/kettle-r${revision}`,
tags: ["catalogue", sku], context: { sku, revision: String(revision) },
});
return { sku, revision, media_library_id: library.id, image_asset_id: asset.asset_id,
spec_file_id: file.id, knowledge_store_id: store.id, publication_state: "published" };
}
const first = await prepare(1, 1.5);
const [row] = await api(`${db}/rest/products?select=*,_version`, "POST", first, { Prefer: "return=representation" });
const next = await prepare(2, 1.8); // Does not change the current product row.
const changed = await api(`${db}/rest/products?id=eq.${row.id}&_version=eq.${row._version}&select=*,_version`,
"PATCH", next, { Prefer: "return=representation" });
if (changed.length !== 1) throw new Error("Concurrent update: read the row again; do not overwrite it");
const [current] = await api(`${db}/rest/products?sku=eq.${sku}&select=*,_version`);
if (current.spec_file_id !== next.spec_file_id || current.revision !== 2) throw new Error("Reference swap failed");
const hits = await api(`${knowledge}/search`, "POST", {
query: "How much water can the kettle hold?", filters: { type: "and", filters: [
{ type: "eq", key: "sku", value: current.sku },
{ type: "eq", key: "revision", value: current.revision },
] },
});
if (!hits.data?.length) throw new Error("No matching indexed content; inspect status and retry search, not upload");
console.log("Current revision", current, "Knowledge hits", hits);
console.log("Media matches", await api(`${media}/search/expression`, "POST", {
expression: `context.sku=${sku} AND context.revision=${current.revision}`, with_field: ["context"],
}));
const downloaded = await fetch(`${base}/file/v1/files/${current.spec_file_id}/content`, {
headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(120000),
});
if (!downloaded.ok || !(await downloaded.text()).includes("1.8 liters")) throw new Error("Download mismatch");
// Current readers now use revision 2; in a real app wait for old readers before retirement.
await api(`${knowledge}/files/${first.spec_file_id}`, "DELETE");
created.attachments = created.attachments.filter(id => id !== first.spec_file_id);
await api(`/file/v1/files/${first.spec_file_id}`, "DELETE");
created.files = created.files.filter(id => id !== first.spec_file_id);
} finally {
// This disposable example removes only resources whose IDs it created.
const failures = [];
async function clean(path) { try { await api(path, "DELETE"); } catch (error) { failures.push(String(error)); } }
if (database) await clean(`/database/v1/table/${database.id}/rest/products?sku=eq.${sku}`);
if (store) for (const id of created.attachments) await clean(`/knowledge/v1/vector_stores/${store.id}/files/${id}`);
for (const id of created.files) await clean(`/file/v1/files/${id}`);
if (store) await clean(`/knowledge/v1/vector_stores/${store.id}`);
if (library) await clean(`/media/v1/libraries/${library.id}`);
if (database) await clean(`/database/v1/table/${database.id}`);
if (failures.length) throw new Error(`Cleanup needs retry:\n${failures.join("\n")}`);
console.log("Cleanup complete (containers retain their recovery window)");
}

Verify the current revision

The script checks the compare-and-swap result, reads revision 2 back, searches Knowledge with SKU and current revision, and compares downloaded content with the expected capacity. It also prints Media expression results with context. Inspect the returned Knowledge text and citations; a ranking score is not a probability. A completed index does not guarantee every query returns a hit.

Readers must first read the current Database row and use its IDs/revision for subsequent requests. There is no transaction spanning the four products. Creating a candidate does not publish it; the row changes only after its new index completes. A stale _version returns an empty update result, which the script treats as failure.

Failure and cleanup

A failed or timed-out index leaves the old row current. A failed search should be diagnosed from its HTTP response and request ID; do not re-upload a ready file to retry a search. The script reports failures and always attempts cleanup, including partially created candidates. It does not claim a live-service availability guarantee.

For a retained catalogue, switch references first, wait for old readers, detach old Knowledge attachments, delete old source Files, and retire old Media assets separately. To remove a product, stop its readers and remove its Database row before those dependencies. This example deletes its whole dedicated containers at the end; the container recovery window is 7 days, not permanent erasure. Cleanup failures include the exact path for retry. Never apply this cleanup to shared containers.

Next steps

Media · File · Database · Knowledge. Service-agent access also requires the appropriate resource bindings; an organization key’s access does not imply every agent has that access.