Friday, 27 June 2025

Salesforce Platform Cache

 

What is Platform Cache?

Platform Cache is temporary memory storage provided by Salesforce for your org. It allows developers to cache frequently accessed data (e.g., record data, session-specific data, or calculations) and access it much faster than querying the database every time.

Types of Platform Cache

Salesforce provides two types of cache:

TypeDescription
Org CacheShared across all users in the org; used for commonly accessed data
Session CacheUnique per user session (browser or API session); used for session-specific data

Benefits of Platform Cache

 .  Reduces Apex processing time
 .  Minimizes redundant database calls (SOQL/SOSL)
 .  Improves performance of Lightning Components and APIs
 .  Helps in managing resource-heavy calculations

Apex Class

public  class ProductCacheService {
    public class ProductWrapper {
        @AuraEnabled public String Id;
        @AuraEnabled public String Name;
        @AuraEnabled public Decimal BasePrice;
    }

    @AuraEnabled
public static ProductWrapper getProductDetailsByName(String productName) {
    if (String.isBlank(productName)) {
        throw new AuraHandledException('Product Name cannot be blank.');
    }

    // Safe alphanumeric cache key
    String sanitizedName = productName != null ? productName.replaceAll('[^a-zA-Z0-9]', '') : '';
    if (String.isBlank(sanitizedName)) {
        throw new AuraHandledException('Product Name must contain at least one alphanumeric character.');
    }

    String key = 'ProductName' + sanitizedName.toLowerCase(); // no special characters allowed

    // Get cache partition
    Cache.OrgPartition part = Cache.Org.getPartition('ProductCachePartition');

    // Try cache first
    ProductWrapper cached = (ProductWrapper) part.get(key);
    if (cached != null) {
        System.debug('Retrieved from cache: ' + cached);
        return cached;
    }

    // Partial match (LIKE)
    List<Product2> products = [
        SELECT Id, Name, Base_Price__c
       FROM Product2
        WHERE Name LIKE :('%' + productName + '%')
        LIMIT 1
    ];

    if (products.isEmpty()) {
        throw new AuraHandledException('No product found with the given name.');

444333333    }


    Product2 product = products[0];

    ProductWrapper wrapper = new ProductWrapper();
    wrapper.Id = product.Id;
    wrapper.Name = product.Name;
    wrapper.BasePrice = product.Base_Price__c;

    part.put(key, wrapper, 600); // store in cache
    System.debug('Stored in cache: ' + wrapper);
    return wrapper;
}

}

ProductSearch.js

public with sharing class ProductCacheService {
    @AuraEnabled
    public static Decimal getProductPrice(String productId) {
        if (String.isBlank(productId)) {
            throw new AuraHandledException('Product ID cannot be blank.');
        }

        //  Create a cache-safe key
        String key = 'Product' + productId.replaceAll('[^a-zA-Z0-9]', '');

        //  Get Platform Cache partition
        Cache.OrgPartition part = Cache.Org.getPartition('ProductCachePartition');

        //  Try from cache
        Decimal cachedPrice = (Decimal) part.get(key);
        if (cachedPrice != null) {
            System.debug('Retrieved from cache: ' + cachedPrice);
            return cachedPrice;
        }

        //  Fetch from DB
        Product2 product = [SELECT Base_Price__c FROM Product2 WHERE Id = :productId LIMIT 1];
        cachedPrice = product.Base_Price__c;

        //  Store in cache for 10 minutes (600 seconds)
        part.put(key, cachedPrice, 600);
        System.debug('Stored in cache: ' + cachedPrice);
        return cachedPrice;
    }
}

import { LightningElement, track } from 'lwc';
import getProductPrice from '@salesforce/apex/ProductCacheService.getProductPrice';

export default class ProductPrice extends LightningElement {
    @track productId = '';
    @track price;
    @track error;

    handleInputChange(event) {
        this.productId = event.target.value;
        this.price = null;
        this.error = null;
    }

    handleGetPrice() {
        if (!this.productId) {
            this.error = 'Please enter a Product ID.';
            return;
        }

        getProductPrice({ productId: this.productId })
            .then(result => {
                this.price = result;
                this.error = null;
            })
            .catch(error => {
                this.error = 'Error retrieving price. Check the Product ID.';
                this.price = null;
                console.error(error);
            });
    }
}

<template>
    <lightning-card title="Product Price Checker" icon-name="utility:money">
        <div class="slds-p-around_medium">
            <lightning-input
                label="Enter Product ID"
                value={productId}
                onchange={handleInputChange}
                placeholder="e.g. 01t5g000009kXyzAAE">
            </lightning-input>

            <lightning-button
                label="Get Price"
                variant="brand"
                onclick={handleGetPrice}
                class="slds-m-top_medium">
            </lightning-button>

            <template if:true={price}>
                <p class="slds-m-top_medium">
                    <strong>Price:</strong> ₹ {price}
                </p>
            </template>

            <template if:true={error}>
                <p class="slds-text-color_error slds-m-top_medium">
                    {error}
                </p>
            </template>
        </div>
    </lightning-card>
</template>

No comments:

Post a Comment