DEV Community

Sean Li
Sean Li

Posted on • Originally published at blog.lcycug.live on

LWC as a Service

Introduction

In this case, we have two lightning components of which one is an Aura and the other is a LWC. The latter one serves as an Account Eligibility Checking service that will be invoked by the Aura.

The Aura component

force-app/main/default/aura/ParentAuraCmp

image-20210814200808888

force-app/main/default/aura/ParentAuraCmp/ParentAuraCmp.cmp

<!--
 - @author Sean Lee
 - @date 2021-08-13
 - @description This component is used to call the lwc service.
 -->
<aura:component description="ParentAuraCmp" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global">
    <aura:attribute name="boolEligible" type="Boolean" default="false" />
    <aura:handler name="init" value="{!this}" action="{!c.checkAccountEligibility}" />
    <c:accountEligibilityService aura:id="service" />
    <h3>Account Eligibility Status</h3>
    <div><strong>{!v.boolEligible}</strong></div>
</aura:component>

Enter fullscreen mode Exit fullscreen mode

force-app/main/default/aura/ParentAuraCmp/ParentAuraCmp.cmp-meta.xml

<?xml version="1.0" encoding="UTF-8" ?>
<AuraDefinitionBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <description>ParentAuraCmp</description>
</AuraDefinitionBundle>

Enter fullscreen mode Exit fullscreen mode

force-app/main/default/aura/ParentAuraCmp/ParentAuraCmpController.js

/**
 * @author Sean Lee
 * @date 2021-08-13
 * @description This component is used to
 */
({
    checkAccountEligibility: function (component) {
        let idAccount = component.get("v.recordId"),
            service = component.find("service"),
            { checkEligibilityStatus } = service;
        if (checkEligibilityStatus) {
            checkEligibilityStatus(idAccount).then((response) => {
                component.set("v.boolEligible", response === true);
            });
        }
    }
});

Enter fullscreen mode Exit fullscreen mode

The LWC service

force-app/main/default/lwc/accountEligibilityService

image-20210814200936869

force-app/main/default/lwc/accountEligibilityService/accountEligibilityService.html

<!--
 - @author Sean Lee
 - @date 2021-08-13
 - @description This component is used to service as an Account Eligibility Service.
 -->
<!-- Account Eligibility Service -->
<template> </template>

Enter fullscreen mode Exit fullscreen mode

force-app/main/default/lwc/accountEligibilityService/accountEligibilityService.js

/**
 * @author Sean Lee
 * @date 2021-08-03
 * @description This component is used to service as an Account Eligibility Service.
 */
import checkEligibility from "@salesforce/apex/AccountService.checkEligibility";
import { ShowToastEvent } from "lightning/platformShowToastEvent";

const checkEligibilityStatus = function (idAccount) {
    return checkEligibility({ idAccount })
        .then((response) => response === true)
        .catch((error) => {
            dispatchEvent(
                new ShowToastEvent({
                    title: "Error happened during checking Account Eligibility",
                    message: error.body.message,
                    variant: "warning"
                })
            );
        });
};
export { checkEligibilityStatus };

Enter fullscreen mode Exit fullscreen mode

force-app/main/default/lwc/accountEligibilityService/accountEligibilityService.js-meta.xml

<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <description>Account Eligibility Service</description>
    <isExposed>false</isExposed>
    <masterLabel>Account Eligibility Service</masterLabel>
</LightningComponentBundle>

Enter fullscreen mode Exit fullscreen mode

The backend supports

AccountService.cls

force-app/main/default/classes/AccountService.cls

/**
 * @author Sean Lee
 * @date 2021-08-13
 * @description This class is used to service as an AccountService.
 */
public with sharing class AccountService {
    private static final List<String> ELIGIBLE_ACCOUNT_NUMBER_LIST = Label.Eligible_Account_Number_List.split(Constants.SEMI_COLON_REGEXP_SPACE_IGNORED);
    @AuraEnabled
    public static Boolean checkEligibility(Id idAccount) {
        return String.isNotBlank(idAccount) && [SELECT COUNT() FROM Account WHERE Id = :idAccount AND AccountNumber IN :ELIGIBLE_ACCOUNT_NUMBER_LIST] > 0;
    }
}

Enter fullscreen mode Exit fullscreen mode

force-app/main/default/classes/AccountService.cls-meta.xml

<?xml version="1.0" encoding="UTF-8" ?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <status>Active</status>
</ApexClass>

Enter fullscreen mode Exit fullscreen mode

Constants.cls

force-app/main/default/classes/Constants.cls

/**
 * @author Sean Lee
 * @date 2021-08-13
 * @description This class is used to serve as a pool of Constant variables.
 */
public with sharing class Constants {
    private Constants() {
    }
    public final static String SEMI_COLON_REGEXP_SPACE_IGNORED = '\\s*;\\s*';
}

Enter fullscreen mode Exit fullscreen mode

force-app/main/default/classes/Constants.cls-meta.xml

<?xml version="1.0" encoding="UTF-8" ?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <status>Active</status>
</ApexClass>

Enter fullscreen mode Exit fullscreen mode

CustomLabels

force-app/main/default/labels/CustomLabels.labels-meta.xml

<?xml version="1.0" encoding="UTF-8" ?>
<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
    <labels>
        <fullName>Eligible_Account_Number_List</fullName>
        <language>en_US</language>
        <protected>true</protected>
        <shortDescription>Eligible Account Number List</shortDescription>
        <value>test</value>
    </labels>
</CustomLabels>

Enter fullscreen mode Exit fullscreen mode

Conclusion

In the demo above, we called the LWC from an Aura, and a Promise was returned. We had to handle it in the Aura to get the response deep from the backend.

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay