Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 28 ยท Platform APIs and Data

The Script API and Common Classes

A tour of the Script API in Salesforce Commerce Cloud: the dw packages, require paths, Logger, Transaction.wrap, collections, Money, quotas and JavaScript limits.

Everything a Commerce Cloud storefront does on the server is done with the Script API: a large set of classes in packages named dw.* that give your JavaScript access to products, baskets, orders, customers, sites, files, services and more. Controllers, models, hooks and jobs all call it. If you know a handful of packages, the conventions for reading and writing data, and the limits the platform enforces, you can read almost any cartridge.

This lesson is a map rather than a catalog. It shows how to load the classes, which ones you will meet every day, how to log, how and why writes happen inside transactions, and what quotas and an older JavaScript engine mean for the way you write code. The platform code is read-only here, because the site cannot run a Commerce Cloud instance. The two stand-ins are plain JavaScript models of transactions and of quotas, and each says what is real and what is simplified. Later lessons use these classes in context: Catalog, Products and Price Books, Basket, Checkout and Order Flow and Customers, Sessions and Profiles.

Loading classes with require

Server scripts are CommonJS modules. Each file can set module.exports, and require loads another module. Three kinds of paths matter:

JavaScript
'use strict';

// 1. Script API classes: "dw/<package>/<Class>"
var Logger = require('dw/system/Logger');
var ProductMgr = require('dw/catalog/ProductMgr');
var Transaction = require('dw/system/Transaction');

// 2. Cartridge code found along the cartridge path
var collections = require('*/cartridge/scripts/util/collections');

// 3. Code in the same cartridge as the current file
var helper = require('~/cartridge/scripts/helpers/priceHelper');

The */cartridge/... form searches the cartridge path from left to right and returns the first file with that name. That is the mechanism that lets an overlay cartridge replace a script. The ~/cartridge/... form stays in the current cartridge, which you use when you want your own file and not an overridden one. Cartridges and the Cartridge Path explains the lookup.

You may also see importPackage(dw.system) or importClass in old code. They work, but they pollute the global scope and hide where a name comes from. Prefer explicit require.

Packages you will use constantly

Package What it holds Typical classes
dw.system Platform services Site, Logger, Transaction, HookMgr, Status, CacheMgr
dw.catalog Products and categories ProductMgr, CatalogMgr, Product, ProductSearchModel
dw.order Baskets and orders BasketMgr, OrderMgr, Basket, Order, ShippingMgr, PaymentMgr
dw.customer Shoppers CustomerMgr, Customer, Profile, AddressBook
dw.web Storefront request helpers URLUtils, Resource, HttpParameterMap
dw.object Custom data CustomObjectMgr, CustomAttributes
dw.util Collections and helpers Collection, ArrayList, HashMap, StringUtils
dw.value Values Money, Quantity
dw.campaign Promotions PromotionMgr
dw.svc Web services LocalServiceRegistry

Classes whose names end in Mgr are managers: entry points with static methods, such as ProductMgr.getProduct('mug-001') or CustomerMgr.getCustomerByLogin('[email protected]'). Their results are objects with methods and properties.

A Rhino convenience worth knowing: a getter such as product.getName() is also available as the property product.name, isMaster() as product.master, and a setter setName(x) as an assignment. Both spellings appear in real code.

JavaScript
var Site = require('dw/system/Site');
var currentSite = Site.getCurrent();
var siteId = currentSite.ID;
var freeShippingFrom = currentSite.getCustomPreferenceValue('freeShippingThreshold');

Site preferences are read through getCustomPreferenceValue, which returns null when no value was set. Always plan for that.

Collections are not arrays

Many Script API methods return a dw.util.Collection (or a List, Set, Map), not a JavaScript array. A collection has length and iterator(), and a List also supports index access, but it has no map, filter or forEach. This surprises people on their first day.

JavaScript
var items = basket.getProductLineItems();

// Works: iterate with the iterator
var iterator = items.iterator();
while (iterator.hasNext()) {
    var pli = iterator.next();
    // ... use pli ...
}

// Works: convert to a real array, then use array methods
var skus = items.toArray().map(function (pli) { return pli.productID; });

// SFRA's helper wraps the common cases
var collections = require('*/cartridge/scripts/util/collections');
var ids = collections.map(items, function (pli) { return pli.productID; });

Queries such as OrderMgr.searchOrders(...) or ProductMgr.queryAllSiteProducts() return a SeekableIterator, which streams results instead of loading them all. Close it with iterator.close() if you stop before it is exhausted, and never convert a huge result into an array. Money is a class too: new Money(19.99, 'USD') is immutable and has add, subtract and multiply. Use it for totals instead of raw JavaScript numbers, and read Money as Integers for the reasoning.

Logging

dw.system.Logger writes to log files that you can read in Business Manager or through WebDAV. A named logger takes a file prefix and a category:

JavaScript
var Logger = require('dw/system/Logger');
var log = Logger.getLogger('orderexport', 'orderexport.sync');

log.debug('Exporting order {0}', order.orderNo);
log.info('Exported {0} orders', count);
log.warn('Slow response from {0}: {1} ms', serviceId, elapsed);
log.error('Export failed for {0}: {1}', order.orderNo, e.message);

The , placeholders are filled from the extra arguments. Which levels are written is set per category in Business Manager (Custom Log Settings), and debug output is normally switched off in production, so verbose debug calls are for development and troubleshooting. Never log secrets, full card data or complete customer records. Logging is covered in Testing, Debugging and Logging.

Transactions

Reads are free, but any change to a persistent object (a profile attribute, a basket line, an order, a custom object) must happen inside a transaction. Outside one, the platform throws an exception when you write. Transaction.wrap opens a transaction, runs your callback, commits when it returns and rolls back when it throws.

JavaScript
var Transaction = require('dw/system/Transaction');

Transaction.wrap(function () {
    var profile = customer.profile;
    profile.custom.newsletterOptIn = true;
    profile.setPhoneHome('+1 555 0100');
});

Write a small transaction around exactly the writes that belong together, and keep slow work (service calls, loops over thousands of records) outside it. A long transaction holds resources and is easy to push past a limit. Transaction.begin(), commit() and rollback() exist for rare cases; wrap is safer because it cannot forget to finish. In SFRA you will see Transaction.wrap around OrderMgr.createOrder(basket), around address saves and around any call that edits a basket.

The first TryIt is a stand-in. It guards an object with a proxy so writes outside a transaction throw, remembers old values and restores them on an error. What is real: the rule "no writes outside a transaction" and the all-or-nothing behavior of wrap. What is simplified: the platform persists to a database with its own isolation rules, and the stand-in does not allow nested wraps, which is a choice of this model, not a statement about the platform.

JS Transaction.wrap: commit or roll back (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

After the failed transaction the profile is exactly as it was before it started, which is the guarantee you rely on when several related records must change together.

Quotas and limits

The platform is multi-tenant: many storefronts share infrastructure, so it protects itself with quotas. They limit what one request or job can do, for example how long a script may run, how large a response may be, and how many times certain expensive APIs may be called. When a threshold is crossed the platform logs a warning, and when an enforced limit is hit it throws an exception that ends the request. Quota usage is visible in Business Manager (Quota Status), and the values differ between request types such as storefront requests and jobs. Do not memorize the numbers; design so that you are far away from them:

  • Fetch data once and reuse it, instead of calling a manager inside a loop for each item.
  • Use search APIs and indexes for lists; never walk the whole catalog in a storefront request.
  • Move bulk work to a job, where limits are far higher, as in Jobs, Feeds and Import/Export.
  • Cache results that are the same for every shopper, covered in Caching and Performance.

The second TryIt models the idea with an invented limit of ten calls. It counts calls to a "database", shows the pattern that wastes them, and the pattern that doesn't. The numbers belong to the stand-in only.

JS A call quota: per-item lookups versus one query (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Writing JavaScript for the server

The server-side engine is based on Rhino, not on V8, and it is the reason server code in SFRA looks older than the JavaScript you write in a browser. Treat it as roughly an ES5 environment with CommonJS, and check what your instance's compatibility mode supports before using newer syntax. Practical rules that keep code portable:

  • Start files with 'use strict';, use var and function expressions, and avoid features you have not verified on the instance (modules with import, async functions, optional chaining).
  • There are no Node.js APIs and no npm packages at run time. Client code is built with npm and webpack, but server scripts are plain files in the cartridge.
  • Expect JSON.parse and JSON.stringify to exist, but not fetch; for HTTP calls use the service framework from Service Framework and Third-Party Integrations.
  • Treat Script API objects as foreign objects: they are not plain JavaScript, so JSON.stringify(basket) does not give you a clean copy. Copy the fields you need into a plain object (this is exactly what SFRA's models do, see Models, Decorators and Helpers).

Because the engine and its supported syntax can change between releases, keep new syntax out of shared code until you have run it on your own sandbox, and let your test setup and linter use the same rules you use in the cartridges.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does require('*/cartridge/scripts/util/collections') do?

    The star form searches the cartridge path in order and returns the first match, so an overlay cartridge can replace the file. The tilde form stays in the current cartridge.
  2. 2. basket.getProductLineItems() returns a dw.util.Collection. How do you safely get a JavaScript array of its items?

    Collections are not arrays and have no map or filter. toArray() gives a real array, or you can use the iterator or SFRA's collections helper.
  3. 3. What happens if you assign profile.custom.nickname outside a transaction?

    Persistent objects may only be modified inside a transaction. Transaction.wrap commits on return and rolls back when the callback throws.
  4. 4. Which approach best protects a storefront request from hitting API quotas?

    Quotas limit how often expensive APIs may be called in a request. Fewer, broader calls plus caching and moving bulk work to jobs keeps you far from the limits.
  5. 5. Why should you avoid putting secrets into log messages?

    Log files persist and are visible to people with access to Business Manager or WebDAV logs, so card data, tokens and personal data do not belong in them.

Summary

  • The Script API is a set of dw.* classes loaded with CommonJS require; */cartridge/... follows the cartridge path and ~/cartridge/... stays local.
  • Managers (ProductMgr, BasketMgr, CustomerMgr, OrderMgr...) are the entry points; getters can be read as properties.
  • Collections are not arrays: iterate, call toArray() or use SFRA's helper; close seekable iterators you do not exhaust.
  • Write to persistent objects only inside Transaction.wrap, keep transactions short, and log with Logger without leaking secrets.
  • Quotas protect the platform: query once, cache, and move bulk work to jobs.
  • Server code runs on an older Rhino-based engine, so write conservative JavaScript and verify newer syntax on your own instance.

Next: Catalog, Products and Price Books