AEM Cloud Service - Pass Request Parameters in React SPA Model JSON url

Goal

Extend the React SPA ModelManager to pass request parameters like Access tokens, Cache killer...

Package Install | Github



Solution

1) Create the maven project for your AEM React SPA...

mvn -B archetype:generate -D archetypeGroupId=com.adobe.aem -D archetypeArtifactId=aem-project-archetype -D archetypeVersion=30 
           -D aemVersion=cloud -D appTitle="Experience AEM Extend Model Client" -D appId="eaem-spa-extend-model-client" 
           -D groupId="apps.experienceaem.sites" -D frontendModule=react -D includeExamples=n -D includeDispatcherConfig=n


2) Add logic for extending the ModelClient in file ui.frontend\src\utils\extend-model-client.tsx

import { ModelClient } from "@adobe/aem-spa-page-model-manager";

export const extendModelClient = () => {
    const client = new ModelClient();
    
    const extend = (modelClient:any) => {
        const fetch = modelClient.fetch as Function;
    
        modelClient.fetch = async function (modelPath:string):Promise<object> {
            try {
                const jsonData = await fetch.call(this, modelPath + "?ck=" + Math.floor(Math.random() * 999999));
                return Promise.resolve(jsonData);
            } catch (err) {
                return Promise.reject(err);
            }
        };
    
        return modelClient;
    };

    const modelClient:ModelClient = extend(client);

    return modelClient;
}

export default extendModelClient;


3) While initializing the ModelManager pass the extended version of ModelClient eg. #4 in following ui.frontend\src\index.js

import extendModelClient from './utils/extend-model-client';

const renderApp = () => {
    ModelManager.initialize({ modelClient : extendModelClient()}).then(pageModel => {
        const history = createBrowserHistory();
        render(
            <Router history={history}>
                <App
                    history={history}
                    cqChildren={pageModel[Constants.CHILDREN_PROP]}
                    cqItems={pageModel[Constants.ITEMS_PROP]}
                    cqItemsOrder={pageModel[Constants.ITEMS_ORDER_PROP]}
                    cqPath={pageModel[Constants.PATH_PROP]}
                    locationPathname={window.location.pathname}
                />
            </Router>,
            document.getElementById('spa-root')
        );
    });
};


No comments:

Post a Comment