Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 28 ยท Practice and Review

Practice Exercises with Solutions

Six Salesforce Commerce Cloud exercises with hints and self-checking solutions: cartridge path, routes, decorators, hooks, caching keys and idempotent job imports.

You learn a platform by using it. This lesson gives you six exercises that cover the core of the track: how code is found, how a request flows, how models are built, how extension points are called, how pages are cached and how jobs stay safe. Each exercise has a task, a hint and a worked solution. Try the task in your own editor before you open the solution. Even a half-working attempt teaches more than reading.

Salesforce B2C Commerce cannot run on this site, so the solutions are self-checking stand-ins written in plain JavaScript. They model the idea (a cartridge path resolver, a route chain, a decorator, a hook manager, a cache, an importer) and print PASS or FAIL for each requirement. They are not the Script API, and each one says where it simplifies. Real platform code appears only in short read-only snippets.

flowchart LR
    A["Where is the code?<br/>Exercise 1"] --> B["How does a request flow?<br/>Exercise 2"]
    B --> C["How is data shaped?<br/>Exercise 3"]
    C --> D["How do we extend?<br/>Exercise 4"]
    D --> E["How do we stay fast?<br/>Exercise 5"]
    E --> F["How do jobs stay safe?<br/>Exercise 6"]

The exercises follow the life of a feature, from file lookup to a safe batch job.

Exercises 1 and 2: finding code and following a request

Exercise 1: resolve a file along the cartridge path. A site has the cartridge path plugin_gift:app_brand:app_storefront_base (leftmost wins). The cartridges contain these files:

Cartridge Files
plugin_gift templates/default/checkout/giftBox.isml
app_brand templates/default/checkout/checkout.isml, scripts/helpers/pricing.js
app_storefront_base templates/default/checkout/checkout.isml, templates/default/home/homePage.isml, scripts/helpers/pricing.js

Write resolve(path, cartridges, file) that returns the name of the cartridge that supplies a file, or null. Then write shadowed() that lists every cartridge containing the file in lookup order, which is what you need when you wonder why your edit in the base cartridge has no effect. Finally, show what changes if the path becomes app_brand:plugin_gift:app_storefront_base. Background: Cartridges and the Cartridge Path.

Hint: split the path on : and take the first cartridge that has the file.

Exercise 2: extend a route without editing it. The base cartridge has a route Checkout-Begin made of two steps: one sets the title, one sets the number of items from the request. Without changing those steps, add (a) a step that runs first and redirects to /cart when the basket is empty, and (b) a step that runs last and adds giftOptions: true to the view data when there is something to buy. The mechanism is explained in SFRA Architecture and Request Flow, and the real-world version uses server.prepend and server.append:

JavaScript
// plugin_gift/cartridge/controllers/Checkout.js (read-only: needs the real platform)
'use strict';

var server = require('server');
server.extend(module.superModule);

server.prepend('Begin', function (req, res, next) {
    // runs before the base route's own steps
    next();
});

server.append('Begin', function (req, res, next) {
    var viewData = res.getViewData();
    viewData.giftOptions = true;
    res.setViewData(viewData);
    next();
});

module.exports = server.exports();

Hint: in the stand-in a step continues the chain by calling next(). A step that redirects simply does not call it.

JS Solutions 1 and 2: path resolver and route chain

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

No output.

Expected output: all lines print PASS, pricing.js is shown as app_brand > app_storefront_base (the brand copy wins, the base copy is shadowed) and the full basket view data is {"title":"Checkout","items":2,"giftOptions":true}. The point of exercise 1 is the order: the first match wins and everything to the right is invisible for that file. The point of exercise 2 is that the plugin never touches the base steps. It only adds steps around them, which is why such a plugin survives upgrades of the base cartridge.

Exercises 3 and 4: models and hooks

Exercise 3: write a decorator. SFRA builds product models by running small decorator functions over an empty object (Models, Decorators and Helpers). Write a badge decorator that adds the product's badge (product.custom.badge) as a property, using null when the badge is missing or none. Compose a model from the list base, price, badge. Then explain why the property must be enumerable by showing what happens to JSON.stringify when it is not.

Hint: decorators use Object.defineProperty(object, name, { enumerable: true, value: ... }).

Exercise 4: a tiny hook manager. Extension points are registered by name and called through HookMgr (Hooks and Extension Mechanisms). Build register, hasHook and callHook. For this stand-in, use this rule: handlers run in registration order (which you fill in cartridge path order), and the chain stops at the first handler that returns an object with error: true. Register three handlers on dw.order.calculate / calculate: the base total, a plugin that grants free shipping from 50.00, and a validator that fails. Show which handlers ran.

Hint: the real platform has its own rules for several implementations of one hook, and they differ between hook types. Check the current documentation before relying on any ordering. The rule above belongs to the stand-in only.

JS Solutions 3 and 4: a decorator and a hook manager

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

No output.

The decorator output shows why the pattern is popular: every property is a small, separately testable piece, and a model for a tile can use ['base', 'price'] while a detail page adds more names. The hook exercise ends with base > plugin_shipping > validator, a total of 5700 and a failed result, because the validator returned an error and the last handler was skipped. In real code, always call HookMgr.hasHook before callHook when a hook is optional.

Exercises 5 and 6: caching and jobs

Exercise 5: build a safe cache key. A product tile is cached for 300 seconds. First write the naive version keyed by product ID only and show the bug: a German shopper sees the price that a US shopper caused to be cached. Then fix the key so it contains everything the output depends on (locale and currency here). Finally handle personalization: the page greets a signed-in customer by name, and that greeting must not end up in the shared cache. Add it after reading the cached part. See Caching and Performance for the real mechanisms (page cache, remote includes, custom caches).

Hint: a cache key must include every input that changes the output; per-person content belongs outside the shared cache.

Exercise 6: an idempotent price import. A feed lists sku,cents rows. Apply it to a price table. Reject rows with a negative or non-integer price or a duplicate SKU, count updated and unchanged, and prove that running the same feed twice changes nothing the second time. Then simulate a crash after the first two rows and show that running the feed again finishes the job without damaging the first two. The reasoning is the same as for Jobs, Feeds and Import/Export and Idempotency.

Hint: compare the new value with the stored value before writing, and make every row's result depend only on the row and the table, never on how many times you ran.

JS Solutions 5 and 6: cache keys and an idempotent import

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

No output.

In exercise 5 the naive cache serves the US price to the German shopper, which on a real site means wrong currency, wrong tax display and, in the worst case, someone else's data. The corrected key includes locale, and the greeting is applied after the cache. Exercise 6 reports updated: 3, unchanged: 0 on the first run and updated: 0, unchanged: 3 on the second. The crash simulation shows the resumable property: rows 1 and 2 are already stored, so the rerun reports them as unchanged and only writes row 3.

How to keep practicing

Change the stand-ins. Make exercise 1 handle a missing cartridge in the path, add a replace step type to exercise 2, let hook handlers in exercise 4 return warnings instead of stopping the chain, or add a size limit to the cache in exercise 5. Then build one of the larger projects, starting with Project: A Plugin Cartridge That Extends Checkout, and read your own code like a reviewer: what happens on a retry, what is cached for whom, and what would break if the base cartridge changed?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The cartridge path is plugin_a:app_brand:app_storefront_base and all three contain the same template. Which one is rendered?

    Lookup goes from left to right and takes the first match. The other copies are shadowed and never used.
  2. 2. Why is a plugin that uses server.append safer to maintain than one that copies the whole base controller?

    A copy freezes the base code at one version. An extension keeps the base route and only adds steps.
  3. 3. A decorator defines a property without enumerable: true. What happens to JSON.stringify(model)?

    JSON.stringify and for-in only see enumerable properties. SFRA decorators set enumerable: true so the data reaches templates and JSON responses.
  4. 4. A cached product tile shows the wrong currency to some shoppers. What is the most likely cause?

    Everything that changes the output must be part of the key. Otherwise the first visitor's version is served to everyone.
  5. 5. What makes an import job safe to run twice?

    When every row's outcome depends only on the row and the current data, a repeat or a rerun after a crash is harmless.

Summary

  • Exercise 1 trains the cartridge path: leftmost match wins, everything else is shadowed.
  • Exercise 2 trains route extension: prepend and append add steps without touching base code.
  • Exercise 3 trains decorators: small enumerable properties composed into a model.
  • Exercise 4 trains hooks: register, check with hasHook, call, and know the platform's ordering rules before relying on them.
  • Exercise 5 trains cache keys: include every input in the key, and keep personal content out of shared cache.
  • Exercise 6 trains idempotent jobs: compare before writing, report bad rows, and make reruns harmless.
  • Every solution is a stand-in; verify platform-specific behavior in the current documentation.

Next: SFCC Interview Questions