Javascript Controllers - luciusBlueAcorn/B2C-exam GitHub Wiki

PROMPTS

  • Can create and troubleshoot Javascript Controllers to add business logic to a site

  • Given a requirement, create a Javascript controller that leverages a script and renders a template/JSON

  • Given a coding scenario, modify a Javascript controller to alter the control logic

Docs

docs

About

  • a server-side script that handles storefront requests

  • manage flow of app

  • create instances of viewModels that process requests and generate responses

  • View Models request data from Digital, convert script API objects into pure JSON objects and apply business logic

  • Two flavors: SFRA SGJC

SFRA Controllers

About

  • Server side

  • create ViewModels to process each request as a route and generate a response

  • route syntax : controller-function

    • example https://localhost/on/demandware.store/Sites-RefArch-Site/default/Hello-World
  • .ds or .js

  • located in controllers folder

Example

'use strict';

var server = require('server');
var cache = require('*/cartridge/scripts/middleware/cache');

server.get('World', cache.applyDefaultCache, function (req, res, next) {
    res.render('mytemplate', {
    	myparam: 'Howdy!'
    });;
    next();
});

module.exports = server.exports();

Rending a JSON String

var server = require('server');
server.get('Show', function(req, res, next) {
 res.json({ value: 'Howdy'});
 next();
});
module.exports = server.exports();

SFRA Res options

res.cacheExpirations - sets cache expiration

res.render(templateName, data) - outputs an ISML template back to the client and assigns data to the pdict

res.json(data) - prints a JSON object back to the screen

res.setViewData(data) - doesn't render anything, but sets the output object

SGJC res options

response.renderJSON response.setContentType('text/html') response.getWriter().printIn('<h1>Howdy</h1>')

Debugging

JS errors logged in the customerror_* log files

Customizing

customizing controllers docs

Override

If you want to avoid executing the middleware of the controller

Extend

When you have inexpensive middleware

To Extend or Override

use module.superModule to import functionality, then override or add (extend) to it

EXTEND EXAMPLE SFRA

// Product.js

'use strict';

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

server.append('Show', function (req, res, next) {
    var viewData = res.getViewData();
    viewData.product.reviews = [{
      text: 'not enough sauce',
      rating: 0
    }]

    res.setViewData(viewData);
    next();
});

module.exports = server.exports();

module.superModule inherits the functionality found from the next Product.js found to the right of this cartridge

server.extend adds the routes found by module.superModule

server.append then modifies the Show route, by adding our addition of properties to the viewData. Whatever the original middleware for the Show route still happens + the additional step we just defined

NOTE We usually use append to customize the ViewData object. But WARNING this could lead to executing a controller twice.

REPLACE example

  • If you are replacing some data of existing functionality, consider this bc of performance
var page = module.superModule;
var server = require('server');
server.extend(page);

server.replace('Show', server.middleware.get, function(req, res, next) {
  res.render('myNewTemplate');
  next();
});

using *

the *prefix tells the system to find the file from the top of the cartridge list

ex: var base = require('*/cartridge/model/product/productBase');

SGJC Controller example

'use strict';

/**
 * @module controllers/BMCustomFeeds
 */

var guard = require('bc_library/cartridge/scripts/guard');
var ISML = require('dw/template/ISML');

function start() {
    ISML.renderTemplate('feeds/configurefeeds.isml',
    {
     myParam: 'Howdy'
    );
}

exports.Start = guard.ensure(['get'], start);

NOTE by passing JSON with myParam, myParam will be loaded on a hashmap named pdict as ${pdict.myParam}

About Guard

Guard wraps controller functions. Acts as a request filter. Invokes the function if guard condition is met.

example : exports.EditProfile = guard.ensure(['get', 'https', 'loggedIn'], editProfile);

SFRA vs SGJC

docs

⚠️ **GitHub.com Fallback** ⚠️