Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 28 ยท Projects

Project: A Plugin Cartridge That Extends Checkout

Build a Salesforce B2C Commerce plugin cartridge: extend a Cart route, add a model decorator, an ISML template, a custom hook and a safe save endpoint.

In this project you build a small but realistic plugin cartridge called plugin_giftmessage. It lets a shopper add a gift message to their order from the cart page. The feature is deliberately modest, because the goal is to practice the shape of every plugin: a cartridge of its own that sits in front of the base storefront, extends an existing route without copying it, adds a model decorator and a template, exposes a hook so other cartridges can customize it, and saves data safely.

You will need the ideas from Cartridges and the Cartridge Path, SFRA Architecture and Request Flow, Models, Decorators and Helpers, Hooks and Extension Mechanisms and Custom Objects and System Object Extensions. The real cartridge code below is read-only on this site, because it needs a B2C Commerce sandbox. The TryIt blocks are stand-ins: a miniature platform in JavaScript that follows the same rules (cartridge path lookup, module.superModule, append, hooks), so you can run the whole flow and check your design. Treat them as a model of the mechanics, not as the platform.

The plan

flowchart LR
    A["Cart-Show<br/>(base route)"] --> B["append in plugin:<br/>add giftMessage to viewData"]
    C["POST Cart-SaveGiftMessage<br/>(new route)"] --> D["csrf check"]
    D --> E["hook app.giftmessage.sanitize"]
    E --> F["Transaction: shipment.custom.giftMessage"]
    B --> G["cart/giftMessage.isml<br/>included by the site cart template"]

One extended route, one new route, one hook, one template.

Requirements:

  1. The cart page knows the current gift message (empty if none).
  2. A shopper can save a message of at most 200 characters.
  3. Input is cleaned by a hook, so a project can replace the rules (for example to forbid certain words) without editing the plugin.
  4. Saving is protected against CSRF and done in a transaction.
  5. The plugin changes no base cartridge file.

Cartridge layout

TEXT
plugin_giftmessage/
  package.json
  hooks.json
  cartridge/
    controllers/Cart.js
    models/giftMessage.js
    models/decorators/giftMessage.js
    scripts/helpers/giftMessageHelpers.js
    scripts/hooks/sanitize.js
    templates/default/cart/giftMessage.isml
    templates/resources/giftmessage.properties
  metadata/shipment-extension.xml

package.json tells the platform where the hooks are:

JSON
{
  "name": "plugin_giftmessage",
  "version": "1.0.0",
  "hooks": "./hooks.json"
}

hooks.json registers an implementation of our own extension point:

JSON
{
  "hooks": [
    { "name": "app.giftmessage.sanitize", "script": "./cartridge/scripts/hooks/sanitize" }
  ]
}

On the site, the plugin joins the cartridge path in front of the base cartridge. If your site cartridge is app_custom, a typical path is app_custom:plugin_giftmessage:app_storefront_base. Order matters: when a file exists in several cartridges, the leftmost wins, and module.superModule points at the next one to the right.

Step 1: the data

The message lives on the shipment as a custom attribute. Define it in a metadata file that you import into the instance (see Custom Objects and System Object Extensions):

XML
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.demandware.com/xml/impex/metadata/2006-10-31">
    <type-extension type-id="Shipment">
        <custom-attribute-definitions>
            <attribute-definition attribute-id="giftMessage">
                <display-name xml:lang="x-default">Gift message</display-name>
                <type>string</type>
                <mandatory-flag>false</mandatory-flag>
                <externally-managed-flag>false</externally-managed-flag>
            </attribute-definition>
        </custom-attribute-definitions>
    </type-extension>
</metadata>

Because shipments belong to the basket and are copied to the order, the message follows the shopper through checkout without more code.

Step 2: the hook

The sanitizer cleans the raw text. It does not HTML-encode it: encoding belongs to the output, where the template knows the context (Security, Sessions and Compliance). It removes control characters, collapses whitespace and cuts to 200 characters.

JavaScript
'use strict';

var MAX_LENGTH = 200;

/**
 * @param {string} text raw input
 * @returns {string} cleaned text
 */
exports.sanitize = function sanitize(text) {
    if (typeof text !== 'string') {
        return '';
    }
    return text
        .replace(/[\u0000-\u001f\u007f]+/g, ' ')
        .replace(/\s+/g, ' ')
        .trim()
        .substring(0, MAX_LENGTH);
};

A site can register another implementation of the same extension point in its own hooks.json; the controller below asks the HookMgr whether one exists and falls back to plain text otherwise.

Step 3: decorator, model and helper

A decorator adds one property to an object (see Models, Decorators and Helpers):

JavaScript
'use strict';

module.exports = function giftMessageDecorator(object, shipment) {
    Object.defineProperty(object, 'giftMessage', {
        enumerable: true,
        value: shipment && shipment.custom && shipment.custom.giftMessage ? shipment.custom.giftMessage : ''
    });
};
JavaScript
'use strict';

var giftMessageDecorator = require('*/cartridge/models/decorators/giftMessage');

function GiftMessageModel(shipment) {
    giftMessageDecorator(this, shipment);
}

module.exports = GiftMessageModel;

The helper keeps the controller thin and holds the write, inside a transaction:

JavaScript
'use strict';

var Transaction = require('dw/system/Transaction');
var HookMgr = require('dw/system/HookMgr');
var GiftMessageModel = require('*/cartridge/models/giftMessage');

function getGiftMessage(basket) {
    return new GiftMessageModel(basket.defaultShipment).giftMessage;
}

function save(basket, rawText) {
    var clean = HookMgr.hasHook('app.giftmessage.sanitize')
        ? HookMgr.callHook('app.giftmessage.sanitize', 'sanitize', rawText)
        : String(rawText || '');

    Transaction.wrap(function () {
        basket.defaultShipment.custom.giftMessage = clean;
    });
    return clean;
}

module.exports = { getGiftMessage: getGiftMessage, save: save };

Step 4: the controller

The plugin's Cart.js extends the base controller instead of replacing it:

JavaScript
'use strict';

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

var BasketMgr = require('dw/order/BasketMgr');
var csrfProtection = require('*/cartridge/scripts/middleware/csrf');
var giftMessageHelpers = require('*/cartridge/scripts/helpers/giftMessageHelpers');

server.append('Show', csrfProtection.generateToken, function (req, res, next) {
    var basket = BasketMgr.getCurrentBasket();
    var viewData = res.getViewData();
    viewData.giftMessage = basket ? giftMessageHelpers.getGiftMessage(basket) : '';
    res.setViewData(viewData);
    next();
});

server.post('SaveGiftMessage', server.middleware.https, csrfProtection.validateAjaxRequest, function (req, res, next) {
    var basket = BasketMgr.getCurrentBasket();
    if (!basket) {
        res.setStatusCode(400);
        res.json({ error: true });
        return next();
    }
    var saved = giftMessageHelpers.save(basket, req.form.giftMessage);
    res.json({ success: true, giftMessage: saved });
    return next();
});

module.exports = server.exports();

server.extend(module.superModule) brings in every route of the next Cart.js on the path. append runs after the base route's steps, so the base Show has already prepared its view data and rendered nothing yet; our step adds a key and the template gets it. SaveGiftMessage is a new route in the same controller, so its URL is Cart-SaveGiftMessage.

Step 5: the template

The plugin ships a snippet. Output uses isprint with explicit encoding, and the token field protects the form:

HTML
<isif condition="${pdict.csrf}">
    <form class="gift-message" action="${URLUtils.url('Cart-SaveGiftMessage')}" method="post">
        <label for="giftMessage">${Resource.msg('label.giftmessage', 'giftmessage', null)}</label>
        <textarea id="giftMessage" name="giftMessage" maxlength="200"><isprint value="${pdict.giftMessage}" encoding="htmlcontent"/></textarea>
        <input type="hidden" name="${pdict.csrf.tokenName}" value="${pdict.csrf.token}"/>
        <button type="submit">${Resource.msg('button.save', 'giftmessage', null)}</button>
    </form>
</isif>

The one integration that cannot live in the plugin is the include line. Your site cartridge's cart template adds <isinclude template="cart/giftMessage"/> where the message should appear. Overlaying a whole base template for one line makes future upgrades harder, so keep that overlay as small as possible and document it in the plugin's README: this is what real plugins ask integrators to do.

Step 6: verify the extension

Because you cannot run the platform here, the stand-in below builds a miniature of it and checks your design: the path order, superModule, append, the hook and the CSRF check.

JS Stand-in: run the plugin on a miniature platform

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

No output.

Read the output against the requirements: the extended controller has the base route plus the new one; Show now carries a giftMessage key and the CSRF block only when the plugin is on the path; saving without the token is rejected and nothing is written; messy whitespace is cleaned by the hook before it is stored.

The second stand-in tests the pure pieces, which is where most of your real unit tests would be (see Testing, Debugging and Logging): the sanitize hook with awkward input, and what happens when a site replaces the hook.

JS Stand-in: unit-test the sanitizer and an overriding hook

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

No output.

Note the markup case: the sanitizer keeps <b> as plain text on purpose. The template's encoding="htmlcontent" turns it into harmless text when printed. Encoding at output is the rule; rewriting input is only for shape and length.

Extending the project

Ideas to practice with, all of which stay inside the plugin pattern: show the message on the order confirmation page and in the order e-mail, add a site preference for the maximum length (see Custom Objects and System Object Extensions), expose the message in an API response through an OCAPI/SCAPI hook for headless storefronts (OCAPI and SCAPI), and add an integration test that posts a message and reads the basket back.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does server.extend(module.superModule) do in the plugin's Cart.js?

    superModule is the same-named file further right on the cartridge path. Extending it keeps all existing routes, and the plugin only adds or appends.
  2. 2. Why does the plugin define its own extension point, app.giftmessage.sanitize?

    A hook is a named seam. The plugin ships a default implementation and any cartridge can register another one for the same name.
  3. 3. Why does the sanitizer not HTML-encode the gift message?

    Storing clean data and encoding when printing keeps the data reusable (e-mail, API) and avoids double encoding.
  4. 4. The cartridge path is app_custom:plugin_giftmessage:app_storefront_base. If both app_custom and the plugin have controllers/Cart.js, what happens?

    The leftmost cartridge with the file is used. It receives the next file to the right as superModule, so each layer should extend the previous one.

Summary

  • A plugin cartridge sits in front of the base cartridge on the path and changes behavior by extending, not copying.
  • server.extend(module.superModule) plus append, prepend or new routes adds behavior to an existing controller.
  • A decorator adds one property to a model; a helper holds the write inside Transaction.wrap.
  • Your own hook extension point (hooks.json plus HookMgr) lets integrators customize rules without editing the plugin.
  • Protect state-changing routes with CSRF middleware, clean input for shape, and encode at output.
  • The unavoidable integration step (the include line in the site template) should be tiny and documented.
  • The TryIt blocks are stand-ins that model path lookup, superModule, append and hooks; the real code needs a sandbox.

Next: Project: Product Badges and Delivery Estimates