Search code examples
aemjcr

JCR_SQL2 example in Javascript?


I'm looking for some sample code using the AEM JCR_SQL2 API in server-side Javascript (NOT Java), i.e. code that starts with use(function() { ... }) and is loaded via data-sly-use=${...}.

All Google results are 100% Java based examples.

What I've already tried: Google "JCR-SQL2 js example" and variations.

Expected result: sample code in Javascript.

Actual result: lots of Java code :-(


Solution

  • If you wanna use server-side JS (what I don't recommend), then you only have to convert the syntax of the Java examples. You interact with the Java-Objects anyway. So the API is the same for JS as for Java. In case you have a HTL component and calling the JS via the Use-API, then several objects are already defined in your JS scope.

    https://helpx.adobe.com/experience-manager/htl/using/global-objects.html

    Here is an JS example to search all core components with a SQL-2 query:

    use(function () {
        var pageName = currentPage.name;
        var title = currentPage.properties.get("jcr:title");
        var resourceName = granite.resource.name;
        var resourceTitle = properties.get("jcr:title");
    
        var componentList = [];
        var componentIter = resolver.findResources("SELECT * FROM [cq:Component] AS c WHERE ISDESCENDANTNODE(c, '/apps/core/wcm')", "JCR-SQL2");
        while (componentIter.hasNext()) {
            var compoenentRes = componentIter.next();
            componentList.push(compoenentRes.getPath());
        }
    
        return {
            pageName: pageName,
            title: title,
            resourceName: resourceName,
            componentList: componentList
        };
    });
    

    The component HTL code to use it, would be:

    <div data-sly-use.info="info.js">
        <p>page name: ${info.pageName}</p>
        <p>title: ${info.title}</p>
        <p>resourceName: ${info.resourceName}</p>
        <p>core components: </p>
        <ul data-sly-list.component="${info.componentList}">
            <li>${component}
        </ul>
    </div>
    

    PS: You probably know, but here you find the Use-API for JS: https://helpx.adobe.com/experience-manager/htl/using/use-api-javascript.html