Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
90 views

2 - Common JS & Controllers

1. Modules allow reusable code snippets and promote code reusability. 2. Modules live in the modules folder or a cartridge's script folder and export functions/properties. 3. The cartridge path determines which cartridges and their modules are available to a site by specifying the precedence. 4. When requiring a module, SFRA searches cartridges based on the cartridge path order to find and load the module.

Uploaded by

Megha Agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

2 - Common JS & Controllers

1. Modules allow reusable code snippets and promote code reusability. 2. Modules live in the modules folder or a cartridge's script folder and export functions/properties. 3. The cartridge path determines which cartridges and their modules are available to a site by specifying the precedence. 4. When requiring a module, SFRA searches cartridges based on the cartridge path order to find and load the module.

Uploaded by

Megha Agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

B2C CC Developer Academy

Common JS, SFRA Modules Lookup, Models &


Controllers

Praveen Gaur, Manager – Partner Practice Development


pgaur@salesforce.com
Forward-Looking Statements
Statement under the Private Securities Litigation Reform Act of 1995:
This presentation contains forward-looking statements about the company’s financial and operating results, which may include expected GAAP and non-GAAP financial and other operating and non-
operating results, including revenue, net income, diluted earnings per share, operating cash flow growth, operating margin improvement, expected revenue growth, expected current remaining
performance obligation growth, expected tax rates, the one-time accounting non-cash charge that was incurred in connection with the Salesforce.org combination; stock-based compensation expenses,
amortization of purchased intangibles, shares outstanding, market growth and sustainability goals. The achievement or success of the matters covered by such forward-looking statements involves risks,
uncertainties and assumptions. If any such risks or uncertainties materialize or
if any of the assumptions prove incorrect, the company’s results could differ materially from the results expressed or implied by the forward-looking statements we make.
The risks and uncertainties referred to above include -- but are not limited to -- risks associated with the effect of general economic and market conditions; the impact of geopolitical events; the impact of
foreign currency exchange rate and interest rate fluctuations on our results; our business strategy and our plan to build our business, including
our strategy to be the leading provider of enterprise cloud computing applications and platforms; the pace of change and innovation in enterprise cloud computing services; the seasonal nature of our sales
cycles; the competitive nature of the market in which we participate; our international expansion strategy; the demands on our personnel and infrastructure resulting from significant growth in our customer
base and operations, including as a result of acquisitions; our service performance and security, including the resources and costs required to avoid unanticipated downtime and prevent, detect and
remediate potential security breaches; the expenses associated with new data centers and third-party infrastructure providers; additional data center capacity; real estate and office facilities space; our
operating results and cash flows; new services and product features, including any efforts to expand our services beyond the CRM market; our strategy of acquiring or making investments in complementary
businesses, joint ventures, services, technologies and intellectual property rights; the performance and fair value of our investments in complementary businesses through our strategic investment portfolio;
our ability to realize the benefits from strategic partnerships, joint ventures and investments; the impact of future gains or losses from our strategic investment portfolio, including gains or losses from
overall market conditions that may affect the publicly traded companies within the company's strategic investment portfolio; our ability to execute our business plans; our ability to successfully integrate
acquired businesses and technologies, including delays related to the integration of Tableau due to regulatory review by the United Kingdom Competition and Markets Authority; our ability to continue to
grow unearned revenue and remaining performance obligation; our ability to protect our intellectual property rights; our ability to develop our brands; our reliance on third-party hardware, software and
platform providers; our dependency on the development and maintenance of the infrastructure of the Internet; the
effect of evolving domestic and foreign government regulations, including those related to the provision of services on the Internet, those related to accessing the Internet, and those addressing data
privacy, cross-border data transfers and import and export controls; the valuation of our deferred tax assets and the release of related valuation allowances; the potential availability of additional tax assets
in the future; the impact of new accounting pronouncements and tax laws; uncertainties affecting our ability to estimate our tax
rate; the impact of expensing stock options and other equity awards; the sufficiency of our capital resources; factors related to our outstanding debt, revolving credit facility, term loan and loan associated
with 50 Fremont; compliance with our debt covenants and lease obligations; current and potential litigation involving us; and the impact of climate change.
Further information on these and other factors that could affect the company’s financial results is included in the reports on Forms 10-K, 10-Q and 8-K and in other filings it
makes with the Securities and Exchange Commission from time to time. These documents are available on the SEC Filings section of the Investor Information section of the company’s website at
www.salesforce.com/investor.
Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements, except as required by law.
Praveen Gaur
Evangelist:
B2C Commerce Cloud,
B2C Multi Cloud Solutions

pgaur@salesforce.com, Manager PPD,


Salesforce
Today’s Agenda

Agenda:

• Common JS Specifications.
Module Objective: • Common JS Modules.
• SFRA Modules:
• What is a Module?
Given a requirement, create and extend
• Cartridge Path
the functionality of a JavaScript controller
• Global Modules
that leverages models, decorators,
• Directory Structure
factories, or helpers following API best
• Exporting & require Modules
practices and renders a template or
returns a JSON response. • Use of ~ * .
• Cartridge Path
• Middleware Functions
• SFRA Routing
• SFRA Controllers
What is CommonJS
Specification for server-side JavaScript

” The CommonJS module specification is the standard used in server-side JS for working with modules.
Modules are powerful, because they let you encapsulate all sorts of functionality, and expose this functionality to other
JavaScript files, as libraries”

• Modules allows reusable snippets of functionality, each testable on its own.

• The huge npm ecosystem is built upon this CommonJS format.


• Extensively used in SFRA.

• Module.exports enables exposing module’s public functions or properties.


CommonJS
Modules

‘’Modules are very cool, because they let you encapsulate all sorts of functionality, and expose this functionality to other
JavaScript files, as libraries.”

• A JavaScript file is a module when it exports one or more of the


symbols it defines i. e. variables, functions, objects.
• Loaded & executed synchronously.
• Dependencies should be loaded first.
• Suitable for server-side JS.
CommonJS & Modules
Code Example

First Define & Export a module

Then Import a module using require.


Let’s see that in action !!
SFRA Modules
• What is a Module?
• Cartridge Path
• Global Modules
• Directory Structure
• Exporting & require Modules
• Use of ~ * .
SFRA Modules
What is a Module

• Conform to the Modules 1.1.1 specifications.


• Promotes reusability.

• A module is a .ds or .js files, living either in the special modules

folder or in a cartridge’s script folder.


• Modules(peer to cartridges folder) folder for Global modules.

• Access modules in your cartridge, in other cartridges, or in


the modules folder.

• Server module lives in modules folder & server name is reserved for this
module only.
• Changes to server module voids support.
SFRA Modules
Cartridge Path(CP)

• To execute the code, CP needs to be configured for each sites.


• Cartridges configured in CP are available to a Site.

• CP decides the precedence for the file/module lookups.


SFRA Modules
Cartridge Path – File lookup

Quiz - Business Requirement:


• Cartridges Cartridge _DE & app_storefront_base to be used for German
site.
• Cartridges Cartridge _GB & app_storefront_base to be used for UK site.
• Cartridges Cartridge _US & app_storefront_base to be used for US site.
SFRA Modules
Cartridge Path – File lookup

• Requirement:
• Cartridges Cartridge _DE & app_storefront_base to be used for German site.
• Cartridges Cartridge _GB & app_storefront_base to be used for UK site.
• Cartridges Cartridge _US & app_storefront_base to be used for US site.

• Solution: Use the cartridge path effectively


• For Germany site, configure the cartridge path as: Cartridge _DE:app_storefront_base
• For US site, configure the cartridge path as: Cartridge _US:app_storefront_base
• For UK site, configure the cartridge path as: Cartridge _GB:app_storefront_base

** Only cartridges mentioned in the site’s cartridge path are effective for the given Site.
SFRA Modules
Cartridge Path – Module Lookup

Module Lookup:
• Executing require() triggers a Module lookup operation.
• Digital server searches for the required JS module. This search is influenced by the cartridge path:

Cartridges on the left takes precedence over the cartridges on right.

Stores.js in app_storefront_base has following line of code:


var StoreHelpers = require('*/cartridge/scripts/helpers/storeHelpers’);

And Cartridge Path: Cartridge_DE:Link_Cartridge:app_storefront_base


All the cartridges have storeHelpers at the same path(as requested).
SFRA Modules
Cartridge Path – Module Lookup

Effective Cartridge Path: Cartridge_DE:Link_Cartridge:app_storefront_base

All the cartridges have storeHelpers at the same path(as requested).

storeHelper.js from Cartridge_DE will be returned,


as it is the left most and Cartridges on the left takes
presidence over the right ones.
SFRA Modules
Suppressing default Cartridge Path behavior

● Even though the current cartridge comes second in the precedence order but you may want to load the
file from current cartridge, use:

§ ~ to load the file from the current cartridge.


§ * to load the file per the cartridge path precedence order.
§ . to load the file relative to the current file.

relative to the current file require('./shipping') or require('../../util')

relative to the current require ('~/cartridge/scripts/cart')


cartridge

from beginning of cartridge require('*/cartridge/scripts/util/array');


path

specific B2C Commerce API require('dw/catalog/CatalogMgr');

specific module or cartridge: require('server');


Controllers
Extending a module

Use of module.superModule
● Use module.supermodule to refer the parent module.
● Parent & child modules should be on the same relative path.
● Child module will be in the cartridge on the Left hand side in
cartridge path, while the parent Module will be in right one.
● In the child module, provide the definition of the additional
functions or override the ones from parent.
● Use exports in child Module to export it’s own & parent’s public
functions, objects & variables.
SFRA Modules
Global Modules

• Global modules are place modules outside of your cartridge.


• Lives in a special folder.
• Enables a sophisticated lookup mechanism.
• Use your most widely used modules as Global ones.

var u = require( 'mymodule’);

• Lookup mymodule directory for a package.json file.


• Checks the value of the main property in the file.
• If there is no package.json or if the main property is missing, load the main file.
• If not fund, continue the search.
• Return the module in the top-level version directory. If not fund, continue the search.
• Search the modules directory in the top level for a mymodule script file.

Package.json in top level directory > main file > independent file > file in modules directory
SFRA Modules
Cartridge Path – DIY Exercise

Stores.js in app_storefront_base has following line of code:


We have covered a lot but still
var StoreHelpers = require('*/cartridge/scripts/helpers/storeHelpers’);
review the
Documentation.
And Cartridge Path: Cartridge_DE:Link_Cartridge:app_storefront_base
All the cartridges have storeHelpers at the same path(as requested).

storeHelper.js from Cartridge_DE will be returned,


as it is the left most and Cartridges on the left takes
presidence over the right ones.
Middleware Functions
Promotes extensibility & enables Routing in SFRA
Middleware Functions
SFRA Middleware Functions

“Middleware literally means anything you put in the middle of one layer of the
software and another.”

• Middlewares in SFRA are inspired from Express.js.


• In SFRA, all the request processing happens through a predefines series of
Middleware functions.
• Middleware functions have access to Request, Response & next
objects/functions.
• Next() executes the middleware succeeding the current middleware.
• Next() is usually called conditionally or at the end of current Middleware
function.
Middleware Functions
Instances of Middleware implementations in SFRA

• A Route is a chain of Middleware functions.


• Promotes code reusability & extensibility in SFRA.
• Replacement for the guard functionality that existed in SiteGenesis
Controllers.
• Some examples of Middleware Implementations:
• Removed <iscache>, caching now is implemented using
Middleware functions.
Lets do a Code Walkthrough !!
• First have a look at the middleware function defined as Global
Module.
• And then understand the functioning of Middleware Function
Routes, SFRA Routing & Controllers
Routes enables the Routing in SFRA
Controllers
MVC Pattern

• SFRA uses the MVC pattern to server the


customer requests.
• Controller: receives the customer requests,
use the helper classes to run business logic.
Sends the model back to View.
• Model: Controllers use the Model to convert
the Output from helper classes to Serialzed
JSON Objects.
• View: View layer renders the ISML, leverages
the Model object to inject the dynamic data in
templates.
Controller
More about Controllers

• Controllers use Models, Forms, ISML Templates & APIs to serve customer requests.
• Controllers must conform to the CommonJS module standard.

• A controller's file extension can be either .ds or .js. Controllers must be located in
the controllers folder at the top level of the cartridge.
• Exported methods for controllers must be explicitly made public to be available to
handle storefront requests.
Routes
What is a Route?
“Routing refers to determining how an application responds to a client request to a particular endpoint, which
is a URI (or path).”

• Each route can have one or more handler functions, which are executed when the route is matched.

• Route definition takes the following structure:

This mechanism of chaining the middleware functions is called Routing.


Controllers
Extending a Controller

Use of server.extend(module.superModule)
● module.superModule provides access to parent
module.
● SFRA controllers enables extensibility & reusability.
● There are 3 main methods used to extend or overwrite
a route:
○ append: extends functionality by executing AFTER
the superModule route
○ prepend: extends functionality by executing
BEFORE the superModule route
○ replace: overrides the superModule route
Lets do a Code Walkthrough !!
• Review the Home-Show controller to understand the
Middleware functions used.
• Review the server.js module & other helper modules.
DIY: Hands-on challenge

• Business Requirement:
• You also need enable the shoopers to set their weather preferences in their account.

• High-level approach:
• Extend the profile object to accommodate the weather preference, create a custom attribute.
• Extend the Account controller to persist & retrieve this preference.

MORE DETAILS

You might also like