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 orders
  • organizationId — 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 its organizationId
  • publish: false keeps new items as drafts
  • retryTimes and retrySleepMs — the number of request attempts and the pause between them when the platform sends no Retry-After; timeoutMs — the response wait limit
  • fetch — your own fetch implementation, 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 site
  • value() — 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 are includes3dModel: true for a variant with the 3D model, the update period path updateMonths and the photo path image
  • 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 key
  • save() — 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 key
  • delete() — 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: true sends all of them
  • gitSources of 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 only throws RangeError
  • An error response after all attempts throws ApiError with the response code status and the error body problem, 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_ERROR with the URL_REQUIRED detail at the value path — an image or a variant file is not given as an address
  • FILES_UNAVAILABLE — the item files are unavailable to the platform
  • FILES_SCAN_REJECTED — the item files failed the platform check, the scanRejections detail 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 is page and size; fulfillment — a single order
  • dropOffPoints, dispatch, cancel and shipmentDocument — drop-off points, handing over, cancelling and the PDF label or waybill of a shipment, as in the PHP client
  • dispatch and cancel retry 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
Was this article helpful?

Did not find the answer to your question?

Create a request