TypeScript client
What it does
The @opotopo/seller-api package is a TypeScript Seller API client for a Node.js site: it uploads the catalog to the platform, withdraws items that dropped out of the catalog and handles orders. It has no dependencies, requests go through fetch. Item files are passed as http(s) addresses; file upload, notifications and data delivery are covered by the PHP client.
The package is open source under the MIT license: code and releases — github.com/AdzerKI/seller-api-typescript, supported Node.js versions — the package page on npm.
Installation
npm install @opotopo/seller-api
The client
import { SellerApiClient } from '@opotopo/seller-api';
const client = new SellerApiClient({
url: 'https://api.opotopo.com',
key: process.env.OPOTOPO_API_KEY!,
organizationId: process.env.OPOTOPO_ORGANIZATION_ID,
});
key— a key of the "API" section with the write listings and remove listings permissions, plus read orders and fulfill orders for ordersorganizationId— the seller organization; without it items are created on behalf of the key organization, for a personal key — on behalf of its owner; the orders of a company come with itsorganizationIdpublish: falsekeeps new items as draftsretryTimesandretrySleepMs— the number of request attempts and the pause between them when the platform sends noRetry-After;timeoutMs— the response wait limitfetch— your ownfetchimplementation, for instance through a proxy; without it — the one built into Node.js
The catalog
A site catalog is an object with the CatalogSource interface: mapping() returns the item mapping, records() — catalog records with the ItemRecord interface as a list or an async iteration.
import type { CatalogMapping, CatalogSource, ItemRecord } from '@opotopo/seller-api';
class DrawingCatalog implements CatalogSource {
mapping(): CatalogMapping {
return {
category: 'opotopoCategoryId',
fields: { sku: 'article', title: 'name', description: 'description', price: 'price' },
attributes: { 'Load capacity, t': 'capacity' },
images: { cover: 'coverUrl', second: 'secondPhotoUrl', gallery: 'photoUrls' },
model3d: { url: 'modelUrl', orientation: 'modelOrientation' },
variants: [
{ name: 'Drawings', price: 'price', files: 'drawingUrls' },
{ name: 'Drawings + 3D', price: 'priceWithModel', files: 'drawingUrls', includes3dModel: true },
],
};
}
async *records(): AsyncIterable<ItemRecord> {
for (const row of await db.drawings()) {
yield { key: () => String(row.id), value: (path) => row[path] };
}
}
}
key()— the stable record key on the sitevalue()— the value at a mapping path- The mapping keys are the same as in the PHP client, the path of your own shop category is
shopCategory, the variant keys areincludes3dModel: truefor a variant with the 3D model, the update period pathupdateMonthsand the photo pathimage - Images and variant files are an http(s) address or a list of addresses; any other value rejects the item before sending
The item registry
The registry is an object with the ItemStore interface: the state of catalog items between runs kept on the site side, for instance in a table of its database.
import type { ItemState, ItemStore } from '@opotopo/seller-api';
const store: ItemStore = {
async load(catalog) {
const rows: ItemState[] = await db.opotopoItems.findMany({ where: { catalog } });
return new Map(rows.map((row) => [row.key, row]));
},
async save(catalog, state) {
await db.opotopoItems.upsert({
where: { catalog_key: { catalog, key: state.key } },
create: { catalog, ...state },
update: state,
});
},
async delete(catalog, keys) {
await db.opotopoItems.deleteMany({ where: { catalog, key: { in: [...keys] } } });
},
};
load()— catalog records by record keysave()— an item record: the record key, article number, listing, item fingerprint, the last submission rejection with details and the time of the last successful one; the unique key is the catalog and the record keydelete()— removes records of items that dropped out of the catalog
Synchronization
import { Synchronizer } from '@opotopo/seller-api';
const synchronizer = new Synchronizer(client, store, 100);
const catalogs = { drawings: new DrawingCatalog() };
let report = await synchronizer.run(catalogs);
report = await synchronizer.run(catalogs, { only: 'drawings' });
report = await synchronizer.run(catalogs, { full: true });
- the third argument is the batch size
- Sending changed items, batches, retries and withdrawing dropped items work as in the PHP client;
full: truesends all of them gitSourcesof the report — the git source of sent package items: the deploy key, the webhook address and version fetch failures, as in the PHP client- An unknown catalog in
onlythrowsRangeError - An error response after all attempts throws
ApiErrorwith the response codestatusand the error bodyproblem, and the run stops - Scheduled runs go through the site server scheduler; runs must not overlap
Rejections
The run SyncReport holds the numbers of created created, updated updated, unchanged skipped and withdrawn archived items and the rejections failures: catalog, article number, code and details. A rejected item is retried by the next run.
VALIDATION_ERRORwith theURL_REQUIREDdetail at the value path — an image or a variant file is not given as an addressFILES_UNAVAILABLE— the item files are unavailable to the platformFILES_SCAN_REJECTED— the item files failed the platform check, thescanRejectionsdetail gives the reason per file:FILE_INFECTED— a virus was found,FILE_SCAN_LIMITS_EXCEEDED— the file or archive exceeds the check limits; replace the file- other codes — the "API reference" of the "API" section
Orders
const week = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const page = await client.fulfillments({ statuses: ['PENDING'], from: week });
for (const order of page.content) {
await client.dispatch(order.id, { carrierName: 'Shop courier', trackingNumber: 'TRK-1' });
}
await client.cancel(fulfillmentId, 'Out of stock');
const label = await client.shipmentDocument(shipmentId, 'LABEL');
fulfillments— orders by statuses and checkout period, newest first, the page ispageandsize;fulfillment— a single orderdropOffPoints,dispatch,cancelandshipmentDocument— drop-off points, handing over, cancelling and the PDF label or waybill of a shipment, as in the PHP clientdispatchandcancelretry a failure with the same idempotency key — the action never runs twice- The site learns of an order status change from the "Order status changed" notification through the PHP client or by polling
fulfillments
Did not find the answer to your question?
Create a request