@rangorithm/product-lens
v0.1.0
Published
Scan a barcode, show the product. A catalog contract your server answers, and a client that renders it.
Downloads
28
Readme
@rangorithm/product-lens
Scan a barcode, show the product.
The Rangorithm phone app reads the barcode. Your server answers what it is — picture, price, where it is on the shelf. This package is the contract between them, plus the plumbing on both ends.
Your product data never leaves your server. There is no Rangorithm catalog, no sync, no upload. You write one resolve function against your own database.
npm install @rangorithm/product-lensexpress is needed on the server. react is needed only for the hook.
Not a pairing flow
@rangorithm/scan-link pairs a phone to a screen: a code, a handshake, a session that expires. A catalog needs none of that. It is a URL and, if you want one, a key — set once, no reconnecting, and it keeps answering from cache when the Wi-Fi drops.
Serve your catalog
import express from "express";
import { createCatalogServer } from "@rangorithm/product-lens/server";
const catalog = createCatalogServer({
name: "Acme WMS",
currency: "MMK",
// Map the key to a store here. Never trust a store id sent by the client —
// shelf locations and prices are per-store, and a phone can claim any id.
verifyKey: async (key) => stores.findByApiKey(key),
// A catalog row without a picture still has to be usable on the floor.
fallbackImageUrl: "https://acme.example.com/no-image.png",
async resolve({ code, gtin14, variants, codeType, store }) {
const rows = await db.item.findMany({
where: { barcode: { in: [code, ...variants] }, storeId: store.id },
});
return rows.map((row) => ({
name: row.name,
image: { url: row.imageUrl },
price: { currency: "MMK", amount: row.price.toString() },
locations: [
{ label: row.zone, aisle: row.aisle, bin: row.bin, qty: row.onHand },
],
fields: [
{ key: "sku", label: "SKU", value: row.sku, kind: "code" },
{ key: "supplier", label: "Supplier", value: row.supplier },
],
updatedAt: row.updatedAt,
}));
},
});
app.use("/catalog", catalog.express());That mounts two routes:
| | |
| ------------------------------------------ | ---------------------------------------------------------------------------- |
| GET /catalog/v1/info | Names the catalog so the phone can show the user what it is about to talk to |
| GET /catalog/v1/lookup?code=…&codeType=… | 200 { products }, or 404 |
Production must be https; http is allowed only on a local network.
The contract
Three things are required, because a card without them cannot answer the question someone scanned a barcode to ask:
type Product = {
code: string;
codeType: string;
name: string;
image: { url: string | null; alt?: string }; // required
price: { currency: string; amount: string }; // required
locations: { label: string; aisle?: string; bin?: string; qty?: number }[]; // required, ≥ 1
fields?: { key: string; label: string; value: string; kind?: FieldKind }[];
updatedAt?: string;
};Everything else your catalog wants to say travels in fields, so adding an attribute never means a new version of this package. An unrecognised kind renders as text.
Money is a decimal string. 0.1 + 0.2 is why a till drawer disagrees with a receipt; the amount is never a float on the wire. A number you pass is stringified for you.
image.url can be null — that means the row had none and you set no fallback. The client draws its own placeholder. Pass onMissingImage: "reject" instead if you would rather treat it as bad data.
One product, several barcodes
The same item is a different number depending on what was printed on it. A UPC-A on a carton and the EAN-13 for the same product differ by a leading zero; UPC-E is a compressed UPC-A entirely. A catalog keyed on one silently misses the others.
Every lookup is therefore widened before it reaches you:
toGtin14("036000291452", "upc-a"); // "00036000291452"
toGtin14("04252614", "upc-e"); // "00042100005264"
gtinVariants("036000291452"); // ["00036000291452", "0036000291452", "036000291452"]
toGtin14("WH-BIN-0042", "code-128"); // null — not a GTIN, match on `code`Match on variants and you find the row whichever form it was stored in.
Read from a client
import { createProductLens } from "@rangorithm/product-lens";
const lens = createProductLens({
url: "https://acme.example.com/catalog",
apiKey: "sk_live_…",
storage: AsyncStorage, // optional: survives a restart. Omit for memory only.
});
const result = await lens.lookup({ code, codeType });Nothing throws. The result says which of four things happened, because they lead to different decisions on the floor:
| { status: "found"; products: Product[]; source: "network" | "cache"; cachedAt?: string }
| { status: "not_found" }
| { status: "offline"; cachedAt?: string }
| { status: "error"; message: string }"Not in the catalog" is not "no signal." Show them differently, and label a cached card as cached — a stale price shown silently is worse than no price. When the catalog is unreachable but the product was seen before, the last-known answer is returned with source: "cache" and the time it was taken.
React
import { useProductLookup } from "@rangorithm/product-lens/react";
const finder = useProductLookup(lens); // pass null before the catalog is configured
finder.lookup(code, codeType); // newest scan always wins the race
finder.state; // idle | not_configured | looking | found | not_found | offline | errorConnecting a phone
parseCatalogConfig reads a URL, a rangorithm://catalog?url=… deep link, or a config QR:
{
"kind": "rangorithm.catalog",
"v": 1,
"url": "https://acme.example.com/catalog",
"key": "sk_live_…"
}There is no handshake, but reach /v1/info and show the operator the host and catalog name before you save it. Every barcode they scan afterwards goes to that address.
Keys
A leaked key can walk your whole catalog, one barcode at a time. A fixed-window limiter is on by default (600 lookups per minute per key) and rateLimit: false turns it off — but the limiter is a speed bump, not a control. Rotating keys is yours to own. Issue one per store, and make revoking one a thing you can do without a deploy.
The default limiter is in memory, so it counts per replica. Run more than one and you want a shared store in front.
Verify
pnpm --filter @rangorithm/product-lens verifyRuns the GTIN rules, the router, keys, caching, and the offline path against a real express server.
License
MIT
