sfra-models.mdcā¢16.1 kB
---
description: Enhanced SFRA model development patterns and best practices with 26+ SFRA documents and model architecture guidance
globs: cartridges/**/models/*.js
alwaysApply: false
---
# Enhanced SFRA Model Development
Use this rule when creating or modifying SFRA models. Now with access to 26+ SFRA documents, smart categorization, and comprehensive model architecture best practices.
## šÆ SFRA Model Override Requirements - MANDATORY MCP VERIFICATION
**CRITICAL**: For ANY SFRA model override, verify paths and patterns with MCP tools:
### Model Override MCP Workflow:
```
MANDATORY sequence for model overrides:
1. ā mcp_sfcc-dev_get_best_practice_guide(guideName: "sfra_models")
2. ā Review "Model Customization Strategies" section
3. ā Confirm proper superModule usage: var base = module.superModule;
4. ā Verify exact override path: cartridge/models/[exact_base_path]
5. ā Generate model ONLY after MCP verification
```
### Model Override Rules from MCP Guide:
- **Use module.superModule**: Always import base model with `var base = module.superModule;`
- **Extend, Don't Replace**: Call base constructor and extend functionality
- **Maintain Interface**: Keep same public API as base model for template compatibility
- **Override Complete Path**: Place model in exact same path as base cartridge
**NEVER create SFRA model overrides without MCP tool verification!**
## ā ļø CRITICAL: Decorator Index.js File Warning
**DANGER**: Avoid creating `index.js` files in the `decorators` folder. This can accidentally override SFRA's main `index.js` file, causing application failures and unexpected behavior.
### The Problem:
- SFRA relies on its core `index.js` file for proper initialization
- Adding an `index.js` in decorators can interfere with SFRA's module resolution
- Can lead to silent failures that are difficult to debug
### Safe Alternative - Direct Import Pattern:
```javascript
'use strict';
var base = module.superModule;
// ā
 SAFE: Import decorator directly
var customDecorator = require('*/cartridge/scripts/decorators/customDecorator');
var productDecorator = require('*/cartridge/scripts/decorators/productDecorator');
function CustomProduct(product, options) {
    base.call(this, product, options);
    
    // ā
 Apply decorators directly
    customDecorator(this);
    productDecorator(this);
}
module.exports = CustomProduct;
```
### What NOT to do:
```javascript
// ā DANGEROUS: Avoid this pattern
var decorators = require('*/cartridge/scripts/decorators'); // Could conflict with SFRA
```
### Best Practices for Decorators:
1. **Import Explicitly**: Always import specific decorator files by name
2. **Use Full Paths**: Specify complete paths to decorator modules
3. **No Index Files**: Never create `index.js` in decorators folder
4. **Namespace Decorators**: Use descriptive names like `productPriceDecorator.js`
## š Enhanced MCP Tools Sequence
**BEFORE writing ANY SFRA model code:**
### Phase 1: Explore SFRA Model Architecture
1. `mcp_sfcc-dev_get_sfra_categories` - Discover all 7 SFRA documentation categories
2. `mcp_sfcc-dev_get_best_practice_guide` with guideName: "sfra_models" - Get comprehensive model patterns and architecture
3. `mcp_sfcc-dev_get_best_practice_guide` with guideName: "performance" - Performance optimization for models
### Phase 2: Research Core SFRA Components
4. `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "core" - Get core SFRA classes for model integration
5. `mcp_sfcc-dev_get_sfra_document` with documentName: "render" - Template rendering with model data
6. `mcp_sfcc-dev_get_sfra_document` with documentName: "querystring" - URL parameter handling in models
### Phase 3: Model Category-Specific Research (based on model type)
**For Product Models:**
- `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "product"
- `mcp_sfcc-dev_get_sfra_document` with documentName: "product-full" - Complete product model structure
- `mcp_sfcc-dev_get_sfra_document` with documentName: "product-bundle" - Bundle product modeling
- `mcp_sfcc-dev_get_sfra_document` with documentName: "product-tile" - Lightweight product display models
- `mcp_sfcc-dev_search_sfra_documentation` with query: "variation" - Product variation handling
**For Cart/Order Models:**
- `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "order"
- `mcp_sfcc-dev_get_sfra_document` with documentName: "cart" - Cart model architecture
- `mcp_sfcc-dev_get_sfra_document` with documentName: "billing" - Billing address models
- `mcp_sfcc-dev_get_sfra_document` with documentName: "shipping" - Shipping models and calculations
- `mcp_sfcc-dev_get_sfra_document` with documentName: "totals" - Order totals and tax models
**For Customer Models:**
- `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "customer"
- `mcp_sfcc-dev_get_sfra_document` with documentName: "account" - Customer account models
- `mcp_sfcc-dev_get_sfra_document` with documentName: "address" - Address model patterns
**For Pricing Models:**
- `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "pricing"
- `mcp_sfcc-dev_get_sfra_document` with documentName: "price-default" - Standard pricing models
- `mcp_sfcc-dev_get_sfra_document` with documentName: "price-range" - Price range modeling
- `mcp_sfcc-dev_get_sfra_document` with documentName: "price-tiered" - Tiered pricing structures
**For Store/Location Models:**
- `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "store"
- `mcp_sfcc-dev_get_sfra_document` with documentName: "store" - Individual store models
- `mcp_sfcc-dev_get_sfra_document` with documentName: "stores" - Store collection models
### Phase 4: Security and Performance
7. `mcp_sfcc-dev_search_best_practices` with query: "security" - Model security patterns
8. `mcp_sfcc-dev_search_best_practices` with query: "performance" - Model performance optimization
9. `mcp_sfcc-dev_search_best_practices` with query: "validation" - Input validation in models
10. `mcp_sfcc-dev_search_sfra_documentation` with query: [specific functionality] - Find relevant model patterns
## š SFRA Model Documentation Categories (26+ documents)
### Available Categories for Model Development:
- **Core** (5 docs): server, request, response, querystring, render - Integration patterns
- **Product** (5 docs): product-full, product-bundle, product-tile, product-search, product-line-items - Product modeling
- **Order** (6 docs): cart, order, billing, shipping, payment, totals - Commerce flow models
- **Customer** (2 docs): account, address - Customer data models
- **Pricing** (3 docs): price-default, price-range, price-tiered - Pricing logic models
- **Store** (2 docs): store, stores - Store/location models
- **Other** (3+ docs): categories, content, locale - Supporting models
## MCP-Enhanced Model Development Workflows
### Workflow 1: Product Model Development
```
1. mcp_sfcc-dev_get_best_practice_guide with guideName: "sfra_models"
2. mcp_sfcc-dev_get_sfra_documents_by_category with category: "product"
3. mcp_sfcc-dev_get_sfra_document with documentName: "product-full"
4. mcp_sfcc-dev_search_sfra_documentation with query: "decorator"
5. mcp_sfcc-dev_search_best_practices with query: "performance"
```
### Workflow 2: Cart/Order Model Development
```
1. mcp_sfcc-dev_get_best_practice_guide with guideName: "sfra_models"
2. mcp_sfcc-dev_get_sfra_documents_by_category with category: "order"
3. mcp_sfcc-dev_get_sfra_document with documentName: "cart"
4. mcp_sfcc-dev_get_sfra_document with documentName: "totals"
5. mcp_sfcc-dev_search_best_practices with query: "validation"
```
### Workflow 3: Customer Account Model Development
```
1. mcp_sfcc-dev_get_best_practice_guide with guideName: "sfra_models"
2. mcp_sfcc-dev_get_sfra_documents_by_category with category: "customer"
3. mcp_sfcc-dev_get_sfra_document with documentName: "account"
4. mcp_sfcc-dev_search_best_practices with query: "security"
```
### Workflow 4: Custom Pricing Model Development
```
1. mcp_sfcc-dev_get_best_practice_guide with guideName: "sfra_models"
2. mcp_sfcc-dev_get_sfra_documents_by_category with category: "pricing"
3. mcp_sfcc-dev_get_sfra_document with documentName: "price-default"
4. mcp_sfcc-dev_search_sfra_documentation with query: "promotion"
```
## Enhanced MCP-Guided Model Template
```javascript
'use strict';
/**
 * [Model Name] Model
 * Purpose: [Brief description of model functionality and data transformation]
 *
 * Implementation based on Enhanced SFRA Model Documentation:
 * - mcp_sfcc-dev_get_best_practice_guide with guideName: "sfra_models"
 * - mcp_sfcc-dev_get_sfra_categories (discovered 7 categories)
 * - mcp_sfcc-dev_get_sfra_documents_by_category with category: "[relevant_category]"
 * - mcp_sfcc-dev_search_best_practices with query: "performance"
 * - mcp_sfcc-dev_search_best_practices with query: "security"
 * - mcp_sfcc-dev_search_best_practices with query: "validation"
 */
var base = module.superModule;
/**
 * Model Constructor
 * @param {dw.catalog.Product|dw.order.Basket|dw.customer.Customer|Object} sourceObject - Source SFCC API object
 * @param {Object} options - Configuration options for model transformation
 * @constructor
 *
 * Model Architecture Pattern:
 * 1. Extend base SFRA model when applicable
 * 2. Transform SFCC API objects to JSON-ready structures
 * 3. Apply decorators for additional functionality
 * 4. Implement caching strategies for performance
 * 5. Add validation for data integrity
 */
function [ModelName](sourceObject, options) {
    base.call(this, sourceObject, options);
    // Model-specific transformations based on MCP research:
    // - Followed patterns from mcp_sfcc-dev_get_sfra_document with documentName: "[relevant_document]"
    // - Applied security patterns from mcp_sfcc-dev_search_best_practices with query: "security"
    // - Implemented performance optimizations from best practice guide
    if (sourceObject) {
        this.transformSourceObject(sourceObject, options);
    }
}
/**
 * Transform source SFCC object to model properties
 * @param {Object} sourceObject - Source SFCC API object
 * @param {Object} options - Transformation options
 * @private
 */
[ModelName].prototype.transformSourceObject = function (sourceObject, options) {
    // Implement transformation logic following SFRA model patterns
    // Pattern discovered from: mcp_sfcc-dev_get_sfra_document with documentName: "[base_model]"
    // Security consideration: Sanitize sensitive data
    // Pattern from: mcp_sfcc-dev_search_best_practices with query: "security"
    // Performance consideration: Lazy load expensive properties
    // Pattern from: mcp_sfcc-dev_search_best_practices with query: "performance"
};
/**
 * Apply decorators for additional functionality
 * @param {Array} decorators - Array of decorator functions
 * @returns {[ModelName]} Enhanced model instance
 */
[ModelName].prototype.applyDecorators = function (decorators) {
    // Decorator pattern implementation
    // Based on research: mcp_sfcc-dev_search_sfra_documentation with query: "decorator"
    var self = this;
    decorators.forEach(function (decorator) {
        if (typeof decorator === 'function') {
            decorator(self);
        }
    });
    return this;
};
/**
 * Validate model data integrity
 * @returns {Object} Validation result with errors array
 */
[ModelName].prototype.validate = function () {
    // Validation logic following SFRA patterns
    // Based on: mcp_sfcc-dev_search_best_practices with query: "validation"
    var errors = [];
    // Implement validation rules specific to model type
    // Pattern from relevant SFRA model documentation
    return {
        valid: errors.length === 0,
        errors: errors
    };
};
/**
 * Convert model to JSON-ready object for template rendering
 * @returns {Object} Plain object suitable for JSON serialization
 */
[ModelName].prototype.toJSON = function () {
    // JSON serialization following SFRA patterns
    // Ensure circular references are handled
    // Remove functions and private properties
    var result = {};
    // Copy public properties only
    Object.keys(this).forEach(function (key) {
        if (key.charAt(0) !== '_' && typeof this[key] !== 'function') {
            result[key] = this[key];
        }
    }.bind(this));
    return result;
};
module.exports = [ModelName];
```
## SFRA Model Development Best Practices
### 1. Model Architecture Patterns
- **Extend Base Models**: Leverage existing SFRA models when possible
- **Decorator Pattern**: Use decorators for optional functionality
- **Factory Pattern**: Implement factory methods for complex model creation
- **Builder Pattern**: Use builders for models with many optional properties
### 2. Performance Optimizations
- **Lazy Loading**: Load expensive properties only when needed
- **Caching Strategy**: Implement appropriate caching for frequently accessed data
- **Batch Operations**: Process multiple items efficiently
- **Index-Friendly APIs**: Use SFCC APIs that leverage database indexes
### 3. Security Considerations
- **Data Sanitization**: Always sanitize user input
- **Sensitive Data Handling**: Never expose passwords or tokens
- **Input Validation**: Validate all input parameters
- **XSS Prevention**: Escape output for template rendering
### 4. Model Testing Patterns
```javascript
// Example test structure for SFRA models
describe('[ModelName] Model', function () {
    it('should transform source object correctly', function () {
        // Test transformation logic
    });
    it('should validate input properly', function () {
        // Test validation rules
    });
    it('should apply decorators correctly', function () {
        // Test decorator application
    });
    it('should serialize to JSON properly', function () {
        // Test JSON conversion
    });
});
```
## Common Model Implementation Patterns
### Product Model Extension
```javascript
// Pattern from: mcp_sfcc-dev_get_sfra_document with documentName: "product-full"
function CustomProduct(product, options) {
    base.call(this, product, options);
    // Add custom properties
    this.customAttribute = product.custom.customAttribute;
    this.calculatedProperty = this.calculateCustomValue();
}
```
### Cart Model Enhancement
```javascript
// Pattern from: mcp_sfcc-dev_get_sfra_document with documentName: "cart"
function CustomCart(basket, options) {
    base.call(this, basket, options);
    // Add custom totals calculation
    this.customTotals = this.calculateCustomTotals(basket);
    this.loyaltyPoints = this.calculateLoyaltyPoints();
}
```
### Customer Model Customization
```javascript
// Pattern from: mcp_sfcc-dev_get_sfra_document with documentName: "account"
function CustomAccount(customer, options) {
    base.call(this, customer, options);
    // Add customer segment information
    this.segment = this.determineCustomerSegment();
    this.preferences = this.buildPreferenceModel();
}
```
## Advanced Model Patterns
### 1. Composite Models
Combine multiple SFCC objects into a single model for complex views.
### 2. View Models
Create specialized models optimized for specific template rendering needs.
### 3. Command Models
Implement models that encapsulate business logic and operations.
### 4. Event-Driven Models
Models that respond to system events and update accordingly.
## Integration with Controllers
```javascript
// Controller integration pattern
server.get('Show', function (req, res, next) {
    // Use MCP-researched model patterns
    var customModel = new CustomModel(sourceObject, {
        // Options based on MCP research
    });
    // Apply decorators discovered through MCP tools
    customModel.applyDecorators(['decorator1', 'decorator2']);
    res.render('template', {
        model: customModel
    });
    next();
});
```
Remember: Always research existing SFRA model patterns using the MCP tools before implementing custom solutions. This ensures consistency with SFRA architecture and leverages proven patterns for optimal performance and maintainability.