Advanced 35 min read

Build the Apex Controller for LWC

By the end of this lesson, you'll be able to:

  • Write an @AuraEnabled controller method exposing the health summary
  • Decide whether it should be cacheable, with reasoning
  • Keep the controller as a thin layer calling the service

Prerequisites: "Secure the Data Access"

A thin controller calling the service

public with sharing class AccountHealthController {
    @AuraEnabled(cacheable=true)
    public static AccountHealthSummary getAccountHealth(Id accountId) {
        return new AccountHealthService().getHealthSummary(accountId);
    }
}

Exactly Module 24's "thin trigger, real logic in the handler" pattern, now applied to a controller: AccountHealthController has exactly one job — exposing AccountHealthService to LWC — with zero actual health-calculation logic living in the controller itself.

Deciding on cacheable, with reasoning

Applying Module 34's rule of thumb: does this method perform an action, or read data? getAccountHealth only reads and aggregates existing data — it performs no DML at all — making it a clear fit for cacheable=true, letting the dashboard load instantly from cache while Salesforce refreshes the data in the background.

The wrapper class needs its own @AuraEnabled fields

public class AccountHealthSummary {
    @AuraEnabled public Integer openCaseCount;
    @AuraEnabled public Decimal averageResolutionDays;
    @AuraEnabled public Decimal totalWonRevenue;
    @AuraEnabled public Integer daysSinceLastActivity;
}

Exactly Module 34's "every field the UI needs also gets @AuraEnabled" lesson — AccountHealthSummary, defined back in Lesson 2 with no UI awareness at all, now needs these annotations added so the LWC can actually read each field from the returned object.

Exercise

As a comment, explain why getAccountHealth is a good candidate for cacheable=true, applying Module 34's rule of thumb.

Show hint

Does the method perform an action, or only read data?

APEX

Build the Apex Controller for LWC Quiz

1. What is the one job of AccountHealthController?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

This lesson exposes AccountHealthService to the actual dashboard component — a thin @AuraEnabled controller, following Module 34's full toolkit.